<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jude Miracle on Medium]]></title>
        <description><![CDATA[Stories by Jude Miracle on Medium]]></description>
        <link>https://medium.com/@judemiracle?source=rss-648cb35fa9b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N-zq1d-ZneoRWQyxCb842w.jpeg</url>
            <title>Stories by Jude Miracle on Medium</title>
            <link>https://medium.com/@judemiracle?source=rss-648cb35fa9b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:56:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@judemiracle/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I built a tool that connects all your local dev services in one command]]></title>
            <link>https://medium.com/@judemiracle/i-built-a-tool-that-connects-all-your-local-dev-services-in-one-command-15a02528ce15?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/15a02528ce15</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[system-programming]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 07:09:47 GMT</pubDate>
            <atom:updated>2026-07-01T07:09:47.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YcvzL-6hK9fMkJhwmbJUg.png" /></figure><p>Every backend developer has the same dead time. You clone a repo. The README says the app needs Postgres, Redis, and an auth service. Now you have a problem that has nothing to do with code: getting all three reachable from localhost.</p><p>Postgres is in a Kubernetes pod. Redis is in a Docker container. The auth service runs on a staging server. Three services, three different locations, three different ways to connect.</p><p>So you run kubectl port-forward in one terminal. You run docker commands in another. You hardcode a staging URL in your .env for the third. Fifteen minutes later you’re finally coding. Tomorrow you do it all again. Next week one of the connections dies silently, and you spend ten minutes figuring out which one.</p><p>That’s why I built tunl. You write a single config file listing where your services are, and one command opens all the tunnels you need. Your app connects to localhost:5432 to reach Postgres, and it doesn’t matter if Postgres is in a pod, a container, or on a server somewhere else.</p><pre>[services.postgres]<br>local_port = 15432<br>target = &quot;remote://127.0.0.1:5432&quot;<br><br>[services.cache]<br>local_port = 9000<br>target = &quot;docker://redis:6379&quot;<br><br>[services.api]<br>local_port = 8080<br>target = &quot;kubectl://default/api-0:8080&quot;</pre><p>Just run tunl --config config.toml and all three ports are ready to go. In this post, I’ll explain how it works and the decisions behind it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*szdFnWNzD9ISsFy9gdIgoA.gif" /></figure><h3>One trait holds the whole thing together</h3><p>The three target types look nothing alike under the hood. A remote host is a TCP connection. A Docker container needs the Docker socket. A Kubernetes pod needs the API server and a connection upgrade. If I let those differences leak into the rest of the code, every part of the program would need to know about all three.</p><p>I gave them one shape instead:</p><pre>#[async_trait]<br>pub trait Target: Send + Sync + std::fmt::Debug {<br>    async fn connect(&amp;self) -&gt; anyhow::Result&lt;Box&lt;dyn AsyncReadWrite&gt;&gt;;<br>    fn describe(&amp;self) -&gt; String;<br>}</pre><p>A target is anything that can return a read-write stream when needed. That’s the whole idea. connect opens the actual connection, whatever that means for the target, and gives you something you can read bytes from and write bytes to. describe provides a label for logging.</p><p>This approach pays off throughout the code. The part of the program that handles client connections and moves data doesn’t care about the target type. It just holds a Box&lt;dyn Target&gt;, calls connect, and uses the stream it gets. When I added Docker Target and later Kubernetes Target, I didn’t have to change that code. Each target lives in its own file and only knows about itself.</p><p>That AsyncReadWrite in the return type is a small piece of glue:</p><pre>pub trait AsyncReadWrite: AsyncRead + AsyncWrite + Send + Unpin {}<br><br>impl&lt;T: AsyncRead + AsyncWrite + Send + Unpin&gt; AsyncReadWrite for T {}impl&lt;T: AsyncRead + AsyncWrite + Send + Unpin&gt; AsyncReadWrite for T {}</pre><p>It says any type that can be read, written, sent between threads, and moved is a valid stream. A TCP socket qualifies. So does an in-memory pipe. The second line means I never write impl AsyncReadWrite by hand. Any type that fits gets it for free.</p><h3>Moving bytes is one function</h3><p>Once a target gives back a stream, the job is to copy bytes between the client and the stream in both directions until one side disconnects. Tokio has a function for this:</p><pre>pub async fn run(<br>    mut local: impl AsyncReadWrite,<br>    mut target: impl AsyncReadWrite,<br>) -&gt; io::Result&lt;()&gt; {<br>    tokio::io::copy_bidirectional(&amp;mut local, &amp;mut target).await?;<br>    Ok(())<br>}</pre><p>copy_bidirectional runs both copy loops in one future. When one side sends EOF, it closes the write half of the other side and drains what is left before returning. That is the right behavior for TCP, where one side can stop sending while still receiving. I could have written the two loops by hand. Reaching for the function that already handles the half-close edge cases was the better call.</p><h3>Three targets, three surprises</h3><p>At first, I thought each target would just be a simple TCP connection. I quickly learned that wasn’t the case.</p><p><strong>Remote</strong> was the easy one and matched my mental model:</p><pre>let stream = TcpStream::connect(&amp;self.address).await?;<br><br>Ok(Box::new(stream))</pre><p><strong>Docker</strong> broke my model on the first test. The obvious approach is to ask Docker for the container’s IP and connect to it. That works on Linux. On macOS the container network lives inside a hidden virtual machine, and those IP addresses do not exist on the host. There is no route to them.</p><p>The fix was to stop trying to reach into the container’s network from outside. Instead, tunl runs nc inside the container and streams its input and output over the Docker socket. The bytes ride the same socket Docker uses for docker exec, which works on every platform. The cost is a requirement: the container image has to ship a nc binary. Minimal images like distroless and scratch have nothing to run, so they are out. I decided cross-platform support was worth that line in the docs.</p><p><strong>Kubernetes</strong> had the most ways to fail and the least code. The kube crate exposes the same port-forward the kubectl command uses, and it returns a stream that already fits AsyncReadWrite. No adapter needed:</p><pre>let mut forwarder = pods.portforward(&amp;self.pod, &amp;[self.port]).await?;<br>let stream = forwarder.take_stream(self.port)?;<br>Ok(Box::new(stream))</pre><p>The work here was not the happy path. It was turning every failure into something a person can act on. A missing pod, an RBAC denial, an unreachable API server, and a pod that is still starting all look like the same opaque error if you let them. So I read the API server’s status code and wrote a real message for each one, with the command to run next:</p><pre>pod default/api-0 not found. check: kubectl -n default get pods<br>forbidden to port-forward default/api-0. your kubeconfig user needs the pods/portforward permission</pre><p>When a tunnel breaks in the middle of the day, that message is all you see. A generic “Connection refused” makes you hunt for the problem. A message like “The pod is not running, here is how to check” saves you time.</p><h3>Reconnection without thinking about it</h3><p>The reason I built this was that hand-rolled tunnels die and stay dead. So tunl reconnects on its own. When a target is down, it retries with a backoff that grows from one second up to fifteen, then connects the moment the target is back.</p><p>One tricky part was deciding what “reconnect” should mean. It covers setting up a new connection, but it doesn’t try to fix a live connection that drops in the middle. If a pod restarts while you’re running a query, that connection ends. The next request opens a new tunnel once the pod is ready. Trying to patch up a broken connection could send bad data to the client, so reconnecting only happens at setup.</p><p>There was one detail I missed at first: if a target is down and the client is waiting, the client might give up and disconnect. Early versions of tunl kept retrying even after the client was gone. The fix was to watch the client connection during backoff and stop as soon as it closes. It’s a small change, but it means the retry loop only runs when it should.</p><h3>Stopping cleanly</h3><p>If you press Ctrl+C, the simple approach is to stop everything right away. But if you do that just after sending a request, that request might be left unfinished.</p><p>tunl gives open connections a moment to finish. When it gets a signal, every tunnel stops accepting new connections, and active transfers have up to five seconds to complete before they’re closed. That window is limited on purpose. Graceful shutdown doesn’t mean waiting forever for one stuck connection. Five seconds is enough for most cases; then it moves on.</p><h3>Why the config is TOML</h3><p>I went back and forth between TOML and YAML. YAML is everywhere in this space, since Kubernetes and Docker Compose both use it. That was the argument for it, and also the argument against it. YAML has sharp edges. Indentation matters, and the same value can be read as a string or a boolean depending on quoting. For a config a person edits by hand at the start of the day, those edges are a tax.</p><p>TOML is simple and clear. Each service is just a block with two keys. There’s no nesting to mess up:</p><pre>[services.postgres]<br>local_port = 15432<br>target = &quot;remote://127.0.0.1:5432&quot;</pre><p>It’s also the format Rust projects use for Cargo.toml, so anyone working on this codebase has seen it before. I chose the format that’s hard to mess up, even if it’s less popular.</p><h3>Small decisions that paid off</h3><p>A few decisions didn’t change what the tool does, but made it much easier to use.</p><p>tunl binds all local ports before starting any tunnels. If a port is already in use, it tells you which one and exits. You never end up with three services working and the fourth failing silently.</p><p>The main logic is in a library, and the binary is just a thin layer on top. This setup lets me properly test reconnection and shutdown. I can create a fake target that fails a certain number of times, then check that the retry loop works, all in memory without needing a network or cluster.</p><p>Logs are easy to read by default, and you can switch to JSON with a --json flag. Each connection log includes the service name and client address, so if two clients use the same service, you can still tell their connections apart.</p><h3>What it does not do</h3><p>I kept the first version focused on purpose. Local ports only bind to IPv4 loopback. Kubernetes targets use a fixed pod name, not a label or service, so if a Deployment changes the pod name, it’s not followed. Docker targets need the nc binary. I wrote down each of these limits because a tool that’s honest about its edges is easier to trust than one that hides them.</p><h3>Closing</h3><p>The whole design comes down to one trait: a target is something that returns a stream. Once that was decided, the proxy, reconnection, and shutdown logic were written once and worked for all three target types without needing to know which was which. Adding a fourth target would just mean one new file and one new line in the parser.</p><p>If you’re tired of juggling terminal tabs that keep dying, the code is on <a href="https://github.com/am-miracle/tunl">GitHub</a>. One config, one command, and every port is forwarded.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15a02528ce15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built a Kubernetes Operator from scratch: here’s what surprised me]]></title>
            <link>https://medium.com/@judemiracle/i-built-a-kubernetes-operator-from-scratch-heres-what-surprised-me-1747dc2a00a0?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1747dc2a00a0</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes-operator]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 06:01:00 GMT</pubDate>
            <atom:updated>2026-06-16T06:01:00.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzNbkGzO805-ZydHYV6UVw.png" /></figure><p>Kubernetes does a great job running workloads. If you ask for three replicas, it keeps three running. If a pod crashes, it restarts it. If a node fails, it reschedules the pod. The control plane always works to match your desired state.</p><p>However, Kubernetes doesn’t know what’s happening inside your app. It can’t see if your image processing queue has 500 items waiting, or if your video encoding pipeline suddenly gets overloaded at 2 a.m. on Black Friday. It simply runs what you’ve told it to run.</p><p>Operators are built to bridge the gap between what Kubernetes knows and what your application actually needs.</p><p>I built one from scratch. Not to ship a product, but to understand how the internals work. The result is scaledjob-operator: an operator that watches a custom resource called ScaledJob, reads the depth of a Redis queue, and automatically creates Kubernetes Jobs to drain it. Queue fills up, Jobs get created. Queue empties, no new Jobs are created, and the running ones finish naturally.</p><p>In this article, I’ll explain what I built, why I built it, and the three biggest surprises I found along the way.</p><h3>Why queue-based autoscaling specifically</h3><p>Kubernetes usually uses the Horizontal Pod Autoscaler (HPA) for autoscaling. HPA adjusts Deployments based on CPU or memory usage, which works well for web servers where traffic matches resource use.</p><p>But many real workloads don’t work that way. Tasks like image resizing, video encoding, email sending, and payment processing are queue-based. Work comes in batches and can be unpredictable. For these, the best scaling signal isn’t CPU; it’s the queue depth, or how many messages are waiting to be processed.</p><p>KEDA is a solid solution for this in production. It’s powerful and well-maintained. But KEDA’s codebase is big and has many layers, so reading it doesn’t quickly show you how the operator pattern works behind the scenes.</p><p>Building a simpler version from scratch really helps you learn. That’s why I chose to do it myself.</p><h3>What scaledjob-operator does</h3><p>You create a ScaledJob resource that looks like this:</p><pre>apiVersion: batch.miracle.dev/v1<br>kind: ScaledJob<br>metadata:<br>  name: image-processor<br>  namespace: production<br>spec:<br>  queueName: image-resize-queue<br>  redisAddress: redis.production.svc.cluster.local:6379<br>  threshold: 10<br>  minReplicas: 0<br>  maxReplicas: 20<br>  jobTemplate:<br>    spec:<br>      template:<br>        spec:<br>          restartPolicy: Never<br>          containers:<br>            - name: worker<br>              image: myapp/image-worker:v1.2.0</pre><p>The operator keeps an eye on this resource. Every time it reconciles, it checks the Redis queue depth, decides how many Jobs should be running, creates more if needed, and updates the resource’s status with the latest info:</p><pre>status:<br>  queueDepth: 47<br>  activeJobs: 4<br>  desiredJobs: 5<br>  lastScaleTime: &quot;2024-01-15T14:32:00Z&quot;<br>  conditions:<br>    - type: Ready<br>      status: &quot;True&quot;<br>      reason: Reconciled<br>    - type: QueueConnected<br>      status: &quot;True&quot;<br>      reason: Connected</pre><p>The scaling math is straightforward: divide the queue depth by the threshold and round up. For example, if the depth is 47 and the threshold is 10, you get ceil(47/10) = 5. Then, make sure the number stays between minReplicas and maxReplicas.</p><p>I used integer ceiling division rather than math.Ceil to avoid floating-point in the hot path:</p><pre>func calculateDesiredJobs(depth int64, spec batchv1.ScaledJobSpec) int32 {<br>    minReplicas := int32(0)<br>    if spec.MinReplicas != nil {<br>        minReplicas = *spec.MinReplicas<br>    }<br><br>    if spec.Threshold &lt; 1 || depth == 0 {<br>        return minReplicas<br>    }<br><br>    // integer ceiling: (n + d - 1) / d<br>    desired := int32((depth + int64(spec.Threshold) - 1) / int64(spec.Threshold))<br><br>    desired = max(desired, minReplicas)<br>    desired = min(desired, spec.MaxReplicas)<br>    return desired<br>}</pre><p>This function is pure. It doesn’t have side effects, make API calls, or read from Redis. Keeping it pure made it easy to test:</p><pre>func TestCalculateDesiredJobs(t *testing.T) {    <br>    tests := []struct {<br>        name     string<br>        depth    int64<br>        spec     batchv1.ScaledJobSpec<br>        expected int32<br>    }{<br>        {&quot;zero depth returns 0&quot;, 0, spec(10, 0, 5), 0},<br>        {&quot;depth below threshold returns 1&quot;, 5, spec(10, 0, 5), 1},<br>        {&quot;depth above max is clamped&quot;, 1000, spec(10, 0, 5), 5},<br>        {&quot;min replicas floor applies at zero depth&quot;, 0, spec(10, 2, 5), 2},<br>    }<br>    // ...<br>}</pre><h3>The three things that surprised me</h3><h3>1. Idempotency is not optional; it changes how you think</h3><p>Before building this, I only understood idempotency in theory. After building the operator, I realized why it’s absolutely necessary.</p><p>The reconcile function runs all the time — not just when you update a ScaledJob, but also when a Job changes state, during regular resyncs every 30 seconds, and when the operator restarts. Your function can’t assume why it was called. If it tries to guess “what changed?” it will eventually get it wrong.</p><p>The best way to approach this is to treat every reconcile as a fresh look at the current state.</p><pre>func (r *ScaledJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {<br>    // Fetch the current state of the ScaledJob<br>    var sj batchv1.ScaledJob<br>    if err := r.Get(ctx, req.NamespacedName, &amp;sj); err != nil {<br>        return ctrl.Result{}, client.IgnoreNotFound(err)<br>    }<br><br>    // Read queue depth right now<br>    depth, err := r.QueueFactory.ForAddress(sj.Spec.RedisAddress).Depth(ctx, sj.Spec.QueueName)<br>    if err != nil {<br>        // Mark condition, requeue sooner than normal<br>        return ctrl.Result{RequeueAfter: 10 * time.Second}, nil<br>    }<br><br>    // Count what&#39;s actually running right now<br>    active := countActiveJobs(controllerOwnedJobs(jobList, &amp;sj))<br><br>    // Calculate what should be running given current depth<br>    desired := calculateDesiredJobs(depth, sj.Spec)<br><br>    // Close the gap — create Jobs until active reaches desired<br>    for active &lt; desired {<br>        job := buildJob(&amp;sj)<br>        ctrl.SetControllerReference(&amp;sj, job, r.Scheme)<br>        r.Create(ctx, job)<br>        active++<br>    }<br><br>    // Always update status, even when nothing changed<br>    sj.Status.QueueDepth = depth<br>    sj.Status.ActiveJobs = active<br>    sj.Status.DesiredJobs = desired<br>    r.Status().Update(ctx, &amp;sj)<br><br>    return ctrl.Result{RequeueAfter: 30 * time.Second}, nil<br>}</pre><p>Notice that the reconciler never checks if the queue depth changed since last time. It doesn’t need to. Instead, it asks, “What is the queue depth right now, and how many Jobs should there be?” This approach always gives the right answer, no matter how often the function runs.</p><p>This also means the operator doesn’t delete running Jobs when the queue is empty. It just stops creating new ones. The running Jobs finish on their own. This isn’t being lazy; it’s the right way to handle batch workloads. Stopping a worker in the middle of a task to save resources is usually a bad idea.</p><h3>2. Interface-driven design is essential, not just a style choice</h3><p>I used to write interfaces in Go out of habit. Building this operator showed me why they’re truly needed here, not just a nice extra.</p><p>The reconciler has to read from Redis. The simple way is to import the Redis client and call it directly. That works, but then you can’t test the reconciler without a real Redis instance. Tests become slow, depend on the environment, and are fragile.</p><p>The alternative is to define what you need as an interface:</p><pre>// Package queue abstracts queue depth reads behind an interface so the<br>// reconciler can be tested without a real Redis instance.<br>package queue<br><br>type Client interface {<br>    Depth(ctx context.Context, queueName string) (int64, error)<br>}<br><br>type Factory interface {<br>    ForAddress(address string) Client<br>}</pre><p>In production, this is implemented with a real Redis client:</p><pre>type RedisClient struct {<br>    client *redis.Client<br>}<br><br>func (c *RedisClient) Depth(ctx context.Context, queueName string) (int64, error) {<br>    return c.client.LLen(ctx, queueName).Result()<br>}</pre><p>For tests, you use a fake client that returns whatever values you need:</p><pre>type FakeClient struct {<br>    DepthValue int64<br>    Err        error<br>}<br><br>func (f *FakeClient) Depth(_ context.Context, queueName string) (int64, error) {<br>    return f.DepthValue, f.Err<br>}</pre><p>The reconciler gets a Factory when it’s created and never interacts with the Redis import directly. It doesn’t know if it’s using a real Redis or a fake one. It just calls Depth() and uses the result.</p><p>This makes tests fast and predictable:</p><pre>newReconciler := func(depth int64, queueErr error) *ScaledJobReconciler {<br>    return &amp;ScaledJobReconciler{<br>        Client:       k8sClient,<br>        Scheme:       k8sClient.Scheme(),<br>        QueueFactory: &amp;queue.FakeFactory{<br>            Client: &amp;queue.FakeClient{DepthValue: depth, Err: queueErr},<br>        },<br>        Clock:    metav1.Now,<br>        Recorder: eventRecorder,<br>    }<br>}<br><br>It(&quot;queue depth 0 creates no Jobs when minReplicas is 0&quot;, func() {<br>    _, err := newReconciler(0, nil).Reconcile(ctx, reconcile.Request{NamespacedName: namespacedName})<br>    Expect(err).NotTo(HaveOccurred())<br>    Expect(listOwned()).To(BeEmpty())<br>})<br><br>It(&quot;Redis error requeues with shorter interval&quot;, func() {<br>    result, err := newReconciler(0, fmt.Errorf(&quot;connection refused&quot;)).Reconcile(ctx, ...)<br>    Expect(err).NotTo(HaveOccurred())<br>    Expect(result.RequeueAfter).To(BeNumerically(&quot;&lt;&quot;, 30*time.Second))<br>})</pre><p>This design also makes it easy to swap out the backend in the future. If you want to support SQS, just implement QueueClient for SQS. The reconciler doesn’t need any changes.</p><h3>3. Owner references are worth more than they look</h3><p>When the operator creates a Job, it sets an owner reference pointing back to the ScaledJob that created it:</p><pre>func buildJob(sj *batchv1.ScaledJob) *k8sbatchv1.Job {<br>    return &amp;k8sbatchv1.Job{<br>        ObjectMeta: metav1.ObjectMeta{<br>            GenerateName: sj.Name + &quot;-&quot;,<br>            Namespace:    sj.Namespace,<br>            Labels:       map[string]string{labelOwner: sj.Name},<br>        },<br>        Spec: sj.Spec.JobTemplate.Spec,<br>    }<br>}<br><br>// In the reconcile loop, after building the job:<br>ctrl.SetControllerReference(&amp;sj, job, r.Scheme)<br>r.Create(ctx, job)</pre><p>It’s only one line of code, but it makes a big difference.</p><p>When you delete a ScaledJob, Kubernetes automatically deletes all the Jobs it owns. You don’t need finalizers, cleanup code in the reconciler, or background processes to watch for deletions. The garbage collector takes care of everything.</p><p>This is more important than it looks. Without owner references, deleting a ScaledJob would leave orphaned Jobs running in the cluster. In a busy cluster with many ScaledJobs from different teams, these orphans can pile up. They use resources and are hard to trace back to their source.</p><p>Owner references also fix a trickier issue: stale Jobs from a ScaledJob that was deleted and then recreated with the same name. If you delete a ScaledJob called image-processor and make a new one with that name, old Jobs might still be running if they haven’t finished. Filtering by label alone would count those old Jobs as part of the new ScaledJob. The solution is to filter by both label and owner UID:</p><pre>func controllerOwnedJobs(jobs k8sbatchv1.JobList, owner *batchv1.ScaledJob) k8sbatchv1.JobList {<br>    owned := k8sbatchv1.JobList{<br>        Items: make([]k8sbatchv1.Job, 0, len(jobs.Items)),<br>    }<br>    for _, job := range jobs.Items {<br>        controllerRef := metav1.GetControllerOf(&amp;job)<br>        if controllerRef != nil &amp;&amp; controllerRef.UID == owner.UID {<br>            owned.Items = append(owned.Items, job)<br>        }<br>    }<br>    return owned<br>}</pre><p>The test for this was one of the more satisfying ones to write:</p><pre>It(&quot;same-label Jobs without matching controller owner are ignored&quot;, func() {<br>    // Create a Job with the right label but no ownerReference<br>    staleJob := &amp;k8sbatchv1.Job{<br>        ObjectMeta: metav1.ObjectMeta{<br>            Labels: map[string]string{labelOwner: resourceName},<br>        },<br>        // ...<br>    }<br>    k8sClient.Create(ctx, staleJob)<br><br>    // depth=10 → desired=1. The stale Job must not count as active.<br>    newReconciler(10, nil).Reconcile(ctx, ...)<br><br>    // Should have created 1 new Job, not 0<br>    Expect(listOwned()).To(HaveLen(2)) // stale + 1 new<br>    Expect(updated.Status.ActiveJobs).To(Equal(int32(1)))<br>})</pre><h3>How the pieces fit together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4qmS7539oSbBJSPUp7_yA.gif" /></figure><p>Here’s how a request moves through the system from start to finish:</p><pre>You create a ScaledJob<br>        ↓<br>Kubernetes stores it (CRD is registered, API server accepts it)<br>        ↓<br>Operator gets a watch event<br>        ↓<br>Reconciler runs:<br>  1. Fetch the ScaledJob<br>  2. Call QueueClient.Depth(queueName) → Redis LLEN → integer<br>  3. List Jobs by label, filter by owner UID → active count<br>  4. calculateDesiredJobs(depth, spec) → desired count<br>  5. Create (desired - active) new Jobs, each with ownerReference<br>  6. Write queueDepth, activeJobs, desiredJobs to Status<br>  7. Set QueueConnected and Ready conditions<br>        ↓<br>Requeue after 30 seconds → repeat forever</pre><p>Each step in this flow lines up with a specific file in the codebase:</p><pre>scaledjob-operator/<br>├── api/v1/scaledjob_types.go          # CRD Go types — Spec, Status, conditions<br>├── internal/<br>│   ├── controller/<br>│   │   ├── scaledjob_controller.go    # Reconcile() — the core loop<br>│   │   ├── scaling.go                 # calculateDesiredJobs() — pure function<br>│   │   ├── jobs.go                    # buildJob(), countActiveJobs(), controllerOwnedJobs()<br>│   │   └── conditions.go              # setCondition(), findCondition()<br>│   ├── queue/<br>│   │   ├── interface.go               # QueueClient and Factory interfaces<br>│   │   ├── redis.go                   # Real Redis implementation<br>│   │   └── fake.go                    # Fake for tests<br>│   └── metrics/<br>│       └── metrics.go                 # Prometheus gauges and counters</pre><h3>Observability from the start</h3><p>One thing I did early was set up Prometheus metrics before considering the project finished. It’s easy to delay observability and then forget about it.</p><p>The operator exposes five metrics:</p><pre>var labelNames = []string{&quot;namespace&quot;, &quot;scaledjob&quot;, &quot;queue&quot;}<br><br>QueueDepth      *prometheus.GaugeVec   // queue items observed on last reconcile<br>ActiveJobs      *prometheus.GaugeVec   // non-terminal Jobs currently running<br>DesiredJobs     *prometheus.GaugeVec   // what the controller wants running<br>ReconcileTotal  *prometheus.CounterVec // total reconcile attempts<br>ReconcileErrors *prometheus.CounterVec // reconcile attempts that errored</pre><p>These five metrics answer the key questions for an on-call engineer: Is the queue draining? Are workers running? Is the operator healthy?</p><p>The operator also sends a few Kubernetes Events for state changes. For example, RedisUnreachable is sent when the queue can’t be reached, QueueConnected is sent on recovery, and CreatedJobs is sent when new Jobs are created. These events are only sent once per transition, not every reconcile. You don’t want to flood the event stream every 30 seconds just to say everything is okay.</p><h3>Testing without a cluster</h3><p>The controller tests use envtest, a real Kubernetes API server running in-process; no cluster required. Combined with the fake QueueClient, every test scenario runs in milliseconds:</p><pre>It(&quot;Redis error sets QueueConnected=False and requeues sooner&quot;, func() {<br>    // First reconcile succeeds so the condition exists<br>    newReconciler(0, nil).Reconcile(ctx, reconcile.Request{...})<br><br>    // Second reconcile simulates Redis going down<br>    result, err := newReconciler(0, fmt.Errorf(&quot;connection refused&quot;)).Reconcile(ctx, ...)<br>    Expect(err).NotTo(HaveOccurred())<br>    Expect(result.RequeueAfter).To(BeNumerically(&quot;&lt;&quot;, 30*time.Second))<br><br>    // Condition should reflect the failure<br>    updated := &amp;batchv1.ScaledJob{}<br>    k8sClient.Get(ctx, namespacedName, updated)<br>    queueCond := apimeta.FindStatusCondition(updated.Status.Conditions, &quot;QueueConnected&quot;)<br>    Expect(queueCond.Status).To(Equal(metav1.ConditionFalse))<br>})</pre><p>There’s also an end-to-end test that runs on a real Kind cluster. It deploys Redis, pushes 30 messages onto a queue, applies a ScaledJob with a threshold of 10, and waits for 3 Jobs to appear. Then it deletes the ScaledJob and checks that all Jobs are cleaned up. This test gives me real confidence that the whole system works together.</p><h3>What I’d tell someone starting their first operator</h3><p>Before you write any code, describe the reconcile function in plain language, not pseudocode, but real sentences. For example: “When this function runs, it will do X, then Y, then Z.” If you can’t explain it clearly, you probably don’t understand the flow well enough to build it yet.</p><p>Keep business logic out of the reconciler itself. In this project, the scaling calculation is a pure function in its own file. Job construction is in its own function, and condition helpers are separate too. The reconciler just brings these pieces together, without containing their logic.</p><p>Test the failure cases first. For example, what happens if Redis goes down, the ScaledJob is deleted during a reconcile, or a Job has the right label but the wrong owner? These edge cases are where operators can fail quietly in production. If you don’t test them during development, you’ll end up fixing them at 2 am.</p><p>You can find the full project at <a href="https://github.com/am-miracle/scaledjob-operator">github.com/am-miracle/scaledjob-operator</a>. The README has local setup instructions and explains every part. If you’re working with Kubernetes and want to really understand operators, building a simple one from scratch is the fastest way to learn. KEDA’s documentation will make a lot more sense afterward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1747dc2a00a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built a tool that tells you if your Kubernetes deploy is about to cause an incident]]></title>
            <link>https://medium.com/@judemiracle/i-built-a-tool-that-tells-you-if-your-kubernetes-deploy-is-about-to-cause-an-incident-f8c3e617edbc?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8c3e617edbc</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Mon, 08 Jun 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-06-08T06:01:01.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0a7Q7jxVjsSn-hdAjAH0A.png" /></figure><p>Every engineer who has deployed to Kubernetes has had this moment: you’re staring at a YAML diff, trying to figure out if that change to spec.template.spec.containers[0].image is fine or if it’s going to take down production at 2 a.m.</p><p>A raw git diff doesn’t help. It shows you text changed. It doesn’t tell you what that means.</p><p>So I built kdiff, a CLI that compares two Kubernetes manifests and tells you not just what changed, but also whether any of those changes are risky.</p><h3>The problem with existing tools</h3><p>kubectl diff compares your local manifest against what’s live in the cluster. That’s useful, but it requires cluster access, and it doesn’t flag risky patterns. It just shows you the diff and leaves the interpretation to you.</p><p>helm diff is similar. It’s great for seeing what a Helm upgrade will do, but its output is just raw, unanalyzed text.</p><p>What I wanted was something more like terraform plan. When Terraform shows you a plan, it doesn’t just say these resources will change. It also tells you which changes are destructive, making the risk clear before you apply anything.</p><p>Kubernetes doesn’t have a tool like that, so kdiff is my attempt to fill that gap.</p><h3>What it does</h3><p>You give it two YAML files, one before and one after, and it tells you:</p><ul><li>Which resources were added, removed, or modified</li><li>For modified resources, exactly which fields changed and what the values were before and after</li><li>A risk analysis flagging anything operationally dangerous</li></ul><p>Here’s what the output looks like on a real example: ⁠ ⁠</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*rR_WE2cXN0Jt_aY8Ep6z6Q.gif" /></figure><p>Four HIGH flags in one diff. This is a deploy that would have caused problems.</p><p>It also supports --output json for CI pipelines and can take a directory as input if you have multiple manifest files.</p><h3>How it’s built</h3><p>The tool is written in Go. Its architecture is a pipeline with five stages, each handling a single job and passing its output to the next.</p><pre>Input Files<br>    ↓<br>Loader    — reads YAML, splits multi-document files on ---<br>    ↓<br>Parser    — turns raw YAML into typed Resource structs<br>    ↓<br>Differ    — compares before/after, produces a list of changes<br>    ↓<br>Risk      — inspects changes for dangerous patterns<br>    ↓<br>Renderer  — formats output for terminal or JSON</pre><p>Each stage is in its own package under internal/. They only interact through shared types, which makes each one independently testable.</p><p>Let me walk through the parts that were actually interesting to build.</p><h3>The diffing problem</h3><p>The naive approach to diffing YAML is to serialize both documents back to strings and run a text diff. That tells you something changed, but not what.</p><p>A better approach is to walk both documents as maps and record every path where values differ. That’s what kdiff does. A field change looks like this:</p><pre>spec.template.spec.containers.api.image   api:v1.2.3 → api:latest</pre><p>That path is meaningful. You know exactly where in the manifest this changed.</p><p>The tricky part is handling Kubernetes lists. A Deployment’s containers field is a YAML array. If you compare arrays by index, you get containers[0].image changed. That’s somewhat useful, but not ideal. If you rename a container or reorder the list, index-based diffing can report many false changes.</p><p>A better approach is to compare lists by the name field that most Kubernetes list items have. Containers, environment variables, and volume mounts all have names. So instead of containers[0], you get containers.api, which is keyed by the container’s actual name.</p><pre>func indexByName(items []any) map[string]any {<br>    result := make(map[string]any, len(items))<br>    for _, item := range items {<br>        m, ok := item.(map[string]any)<br>        if !ok {<br>            continue<br>        }<br>        name, ok := m[&quot;name&quot;].(string)<br>        if ok &amp;&amp; name != &quot;&quot; {<br>            result[name] = m<br>        }<br>    }<br>    return result<br>}</pre><p>If every item in a list has a name field, compare by name. If the list is mixed or unnamed, treat the whole list as a single value and report one change at the list path. This avoids silent data loss and prevents errors on unexpected shapes.</p><h3>The namespace problem</h3><p>Kubernetes has a subtlety that catches people out: if you don’t specify metadata.namespace in a manifest, it defaults to default when applied to the cluster.</p><p>This means a manifest with namespace: default and one with no namespace at all describe the same resource. If you compare them without handling this, you get a false Removed and Added for the same resource, which is both incorrect and noisy.</p><p>kdiff normalizes this. When matching resources for comparison, it treats a missing namespace as default for namespaced resource kinds. But cluster-scoped resources like Node and ClusterRole don’t have namespaces at all, so they get different handling.</p><p>This also affects the body diff. If the before manifest omits metadata.namespace and the after manifest includes namespace: default, the raw YAML bodies differ, but semantically they’re identical. So before comparing the body, kdiff removes metadata.namespace from both sides. The field is already part of the resource’s identity, so including it in the body diff would produce false positives.</p><p>It’s a small detail, but it matters if you want output that people can actually trust.</p><h3>The risk model</h3><p>The risk analyzer is the part that makes kdiff more than just a diff viewer.</p><p>Each risk rule is a function with the same signature:</p><pre>type rule func(diff.Change) []RiskFlag</pre><p>Rules are collected in a slice and checked in order against every change. To add a new rule, you just write one function and add it to the slice. There are no switch statements to change and no existing logic to update.</p><pre>var rules = []rule{<br>    ruleResourceDeleted,<br>    ruleReplicaDecreased,<br>    ruleImageUnpinned,<br>    ruleImageChanged,<br>    ruleEnvVarRemoved,<br>    ruleResourceLimitsChanged,<br>    ruleProbeRemoved,<br>    ruleStrategyTypeChanged,<br>    ruleVolumeMountRemoved,<br>    ruleTerminationGracePeriodDecreased,<br>}</pre><p>Each rule is independently testable. Here’s the replica rule:</p><pre>func ruleReplicaDecreased(c diff.Change) []RiskFlag {<br>    if c.Type != diff.Modified {<br>        return nil<br>    }<br>    for _, f := range c.Fields {<br>        if !f.Path.Equals(&quot;spec&quot;, &quot;replicas&quot;) {<br>            continue<br>        }<br>        before, bOK := toInt64(f.Before)<br>        after, aOK := toInt64(f.After)<br>        if bOK &amp;&amp; aOK &amp;&amp; after &lt; before {<br>            return []RiskFlag{{<br>                Severity: High,<br>                Rule:     &quot;replica-decreased&quot;,<br>                Message:  fmt.Sprintf(&quot;replicas decreased from %d to %d&quot;, before, after),<br>                Path:     f.Path.String(),<br>            }}<br>        }<br>    }<br>    return nil<br>}</pre><p>Each rule has a single concern. The replica rule only triggers when replicas go down. Increasing replicas is fine. Changing replicas on a resource that’s being deleted is already handled by the resource-deleted rule. Each rule stays focused on its own job.</p><p>The image rules are worth calling out specifically because there are two of them that often fire together:</p><ul><li>image-unpinned triggers when the new image uses :latest or has no tag at all. It does not trigger for digest-pinned images (image@sha256:...) because a digest is content-addressed and is immutable by definition.</li><li>image-changed triggers when the image changes to any new value, with MEDIUM severity. It’s not dangerous by itself, but it’s the most common source of production incidents during deploys. You want to be aware of it.</li></ul><p>A single image change from api:v1.2.3 to api:latest fires both rules. You see that the image changed, and you see that the new reference is not reproducible.</p><h3>Handling malformed input</h3><p>Real YAML is messy. The tool needs to handle it without panicking.</p><p>Two cases worth mentioning:</p><p><strong>Non-string image fields </strong>can be tricky.<strong> </strong>For example, image: [list] is valid YAML. Comparing two []any values with == will cause a panic in Go. The image rules check that both before and after values are strings before comparing them. If they’re not, the rule simply skips them.</p><p><strong>Non-integer replica counts </strong>are another case.<strong> </strong>For example, replicas: &quot;three&quot; is parsed as a string. The replica rule uses a toInt64 helper that handles int, int64, and float64, which are the three types the YAML parser can produce for a numeric field, and returns a boolean to show if conversion worked. If either side isn’t numeric, the rule doesn’t trigger.</p><pre>func toInt64(v any) (int64, bool) {<br>    switch n := v.(type) {<br>    case int:<br>        return int64(n), true<br>    case int64:<br>        return n, true<br>    case float64:<br>        return int64(n), true<br>    }<br>    return 0, false<br>}</pre><p>Small helpers like this are what make the difference between a tool that only works on your test data and one that works in the real world.</p><h3>Testing</h3><p>The test suite has around 90 tests. Most of them test failure modes, not just happy paths.</p><p>A few I’m particularly glad I wrote:</p><p>TestCheckDuplicates_OmittedNamespaceMatchesExplicitDefault checks that a file containing two resources that are actually the same (one with namespace: default, one without) is caught as a duplicate instead of silently overwriting one with the other.</p><p>TestDiffCmd_NonStringImageField_DoesNotCrash sends a non-string image value through the full pipeline and checks that the tool produces valid JSON instead of panicking.</p><p>TestCompare_OmittedNamespaceDoesNotProduceModified caught an actual bug. The resource identity matching was correct, but the body diff was still producing a false Modified because metadata.namespace was present in one body and missing in the other. This test is the reason bodyForDiff exists.</p><p>Tests that catch real bugs during development are more valuable than tests written after the fact.</p><h3>Install and try it</h3><pre>go install github.com/am-miracle/kdiff@latest</pre><pre>kdiff diff before.yaml after.yaml<br>kdiff diff before/ after/<br>kdiff diff before.yaml after.yaml --output json</pre><p>The repo is at <a href="https://github.com/am-miracle/kdiff">github.com/am-miracle/kdiff</a>. The README documents every risk rule, its triggers, and why.</p><h3>What’s next</h3><p>There are a few things on the list for future versions:</p><ul><li>Recursive directory traversal (currently, it only reads the top level of a directory)</li><li>Helm and Kustomize rendering support: render first, then pipe to kdiff</li><li>Custom risk rule definitions via a config file</li><li>GitHub Action: For now, the v1 scope is intentional. A focused tool that does one thing well is more useful than a sprawling tool that does many things only halfway. Does many things halfway.</li></ul><p>If you deploy to Kubernetes and you’ve ever stared at a YAML diff trying to figure out if it’s safe, give it a try. I’d be curious what risk patterns you think are missing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8c3e617edbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built a Reverse Proxy in Rust to learn what production traffic actually demands]]></title>
            <link>https://medium.com/@judemiracle/i-built-a-reverse-proxy-in-rust-to-learn-what-production-traffic-actually-demands-40284d4c0dca?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/40284d4c0dca</guid>
            <category><![CDATA[buildinpulic]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[systems-engineering]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Sun, 24 May 2026 19:54:11 GMT</pubDate>
            <atom:updated>2026-05-24T19:54:11.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VA3Qbr9UdiMc76o2" /><figcaption>Photo by <a href="https://unsplash.com/@imperioame?utm_source=medium&amp;utm_medium=referral">Mario Amé</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most backend projects treat the proxy layer like a black box. Requests come in, traffic gets forwarded, and as long as the app responds, nobody looks too closely at what happens in between. I wanted to understand that layer properly, so I built my own reverse proxy in Rust.</p><p>What started as a way to learn request routing and load balancing turned into something more useful. Once you stop treating traffic as a happy-path problem, the real questions show up fast: what happens when a backend starts flapping, when a client uploads too slowly, when an upstream hangs, or when you need to shut the system down without dropping in-flight requests?</p><p>Building this pushed me to think less like an application developer and more like an engineer responsible for traffic, failure, and control.</p><p>The full project is on <a href="http://github.com/am-miracle/ferrum-proxy">GitHub</a></p><h3>What I built</h3><p>I built ferrum-proxy, a reverse proxy written in Rust. It sits in front of backend services, accepts HTTP requests, matches them to routes, selects a healthy backend, forwards the request, and streams the response back to the client.</p><p>At a high level, the request path does a few things in sequence: assign a request ID, reject invalid or oversized input early, match a route, and then decide whether the request can be forwarded once or needs retry-aware handling.</p><pre>pub async fn handle_request&lt;B&gt;(mut request: Request&lt;B&gt;, state: AppState) -&gt; Response&lt;ProxyBody&gt;<br>where<br>    B: hyper::body::Body&lt;Data = Bytes&gt; + Send + Sync + &#39;static,<br>    B::Error: std::error::Error + Send + Sync + &#39;static,<br>{<br>    state.telemetry.record_request();<br><br>    let request_id = request<br>        .headers()<br>        .get(&quot;x-request-id&quot;)<br>        .and_then(|v| v.to_str().ok())<br>        .map(str::to_string)<br>        .unwrap_or_else(next_request_id);<br><br>    let method = request.method().clone();<br>    let path = request.uri().path().to_string();<br><br>    if let Some(content_length) =<br>        content_length_exceeds(request.headers(), state.upstream.max_request_body_bytes())<br>    {<br>        return complete_request(/* trimmed */);<br>    }<br><br>    let Some(route) = match_route(&amp;path, &amp;state.config.routes) else {<br>        return complete_request(/* trimmed */);<br>    };<br><br>    if should_retry_request(&amp;state, &amp;method) {<br>        // buffer once, then retry safely if policy allows it<br>    } else {<br>        // forward directly on the fast path<br>    }<br>}</pre><p>I like this snippet because it shows the project for what it is: not just a server that forwards bytes, but a system that enforces policy before traffic ever reaches an upstream.</p><p>Under the hood, I added path-based routing, round-robin load balancing, active and passive health checks, bounded retries for safe requests, request and response size limits, timeout handling, graceful shutdown, and Prometheus-style metrics. I also built benchmark tooling around the live proxy so I could measure throughput and latency under different scenarios instead of guessing.</p><h3>Why I built it</h3><p>I built it because I wanted to get closer to the kind of engineering problems that only show up once software has to deal with real traffic. A lot of backend work lives behind frameworks and managed infrastructure, which is useful, but it can also hide the mechanics that shape reliability and performance.</p><p>I did not want to build another demo project where everything works as long as nothing goes wrong. I wanted to work on the part of the stack where failures are normal, tradeoffs matter, and small design decisions have visible consequences. Writing a reverse proxy forced me to think about timeouts, retries, streaming, backpressure, unhealthy backends, and shutdown behavior as first-class concerns.</p><p>This project was also a way to make my engineering taste visible. I wanted something that showed more than syntax or framework familiarity. I wanted a project that reflected how I think about systems: build the core path carefully, measure it, test it under realistic conditions, and be honest about what still needs improvement.</p><h3>Core features</h3><p>The proxy supports path-based routing, so incoming requests can be mapped to different backend pools based on URL prefixes. Once a route is matched, traffic is distributed with round-robin load balancing across healthy backends.</p><p>I added both active and passive health checks. Active checks probe backend health endpoints in the background, while passive checks react to failures seen in real traffic. That made it possible to remove unstable backends from rotation and bring them back once they recovered.</p><p>The request path supports streaming for both inbound and outbound traffic, with explicit size limits and timeout handling to avoid letting slow or abusive clients hold resources indefinitely. I also added bounded retries for safe requests, graceful shutdown with connection draining, and Prometheus-style metrics so the system can be observed while it is under load.</p><p>To make performance work concrete, I built a benchmark workflow around the live proxy using wrk. That let me measure latency and throughput across healthy traffic, retries, large responses, and request uploads instead of relying on assumptions.</p><h3>Engineering decisions</h3><p>Rust felt like the right choice for this project because the problem space is concurrency-heavy, IO-bound, and sensitive to correctness. A reverse proxy has to manage many connections at once, move data efficiently, and stay predictable under failure. Rust gave me low-level control without forcing me to accept memory unsafety as the cost.</p><p>One of the biggest decisions was to treat streaming as the default instead of buffering everything up front. That matters for latency, memory usage, and behavior under larger payloads. At the same time, I had to be selective about where buffering was necessary, especially for retryable requests, because replaying a request safely requires a different tradeoff than simply forwarding it once.</p><p>I was also careful about where to draw boundaries around retry logic and health behavior. That tradeoff shows up directly in the retry path. I did not want retries to be open-ended or invisible. The proxy only retries within a bounded budget, keeps track of which backends have already been tried, and stops once the request is no longer safe or useful to replay.</p><pre>async fn forward_with_retries(<br>    state: &amp;AppState,<br>    route: &amp;RouteConfig,<br>    method: &amp;Method,<br>    path: &amp;str,<br>    request: Request&lt;Bytes&gt;,<br>    client_addr: Option&lt;SocketAddr&gt;,<br>    started: Instant,<br>    client_body_timeout: Duration,<br>    request_id: &amp;str,<br>) -&gt; Response&lt;ProxyBody&gt; {<br>    let replayable = ReplayableRequest::from(request);<br>    let max_attempts = state.config.retry.max_attempts;<br>    let total_timeout = Duration::from_millis(state.config.retry.total_timeout_ms);<br>    let mut attempted_backends = HashSet::new();<br>    let mut attempt = 1usize;<br><br>    loop {<br>        if started.elapsed() &gt;= total_timeout {<br>            return complete_request(/* retry budget exhausted */);<br>        }<br><br>        let backend = match select_backend(state, route, Some(&amp;attempted_backends)) {<br>            Some(backend) =&gt; backend,<br>            None =&gt; return complete_request(/* no healthy backends left */),<br>        };<br>        attempted_backends.insert(backend.clone());<br><br>        let response = forward_request(/* trimmed */).await;<br>        let status = response.status();<br><br>        if !should_retry_response(state, status) || attempt &gt;= max_attempts {<br>            return response;<br>        }<br><br>        attempt += 1;<br>    }<br>}</pre><p>I like this part because it reflects the kind of decision-making I care about in systems work. The question is not “can I add retries?” It is “how do I add retries without making failure behavior worse?”</p><p>Retrying everything is easy to implement and dangerous in practice. I limited retries to safer request types and kept them inside a bounded timeout window. The same thinking applied to backend health: the goal was not just to mark things healthy or unhealthy, but to make failure handling stable enough that the proxy would not amplify backend problems.</p><p>Another important decision was how to measure the system. I chose to benchmark the live proxy with wrk instead of relying on function-level microbenchmarks, because the real costs are in sockets, HTTP parsing, routing, forwarding, streaming, retries, and logging under load. That gave me results that were much closer to how the system would actually behave in practice.</p><h3>What was hard</h3><p>The hardest part was that none of the interesting problems were isolated. Almost every feature touched something else. Retries affected buffering. Buffering affected memory pressure. Health checks affected load balancing. Timeouts affected both correctness and user experience. Even graceful shutdown turned into more than just “stop the server” once in-flight requests had to be handled properly.</p><p>Header handling was another place where the project became more real than it looked at first. A proxy cannot just forward everything blindly. Connection-specific headers, forwarding headers, and host information all have to be handled deliberately, or the proxy starts creating subtle correctness problems between clients and upstreams.</p><p>Failure handling was also harder than the happy path. It is easy to proxy a request when both client and backend behave normally. It is much harder to decide what should happen when a backend hangs, when a client sends data too slowly, or when one backend starts failing intermittently. Those are the situations that shape whether a system is trustworthy.</p><p>The other difficult part was performance measurement. It is tempting to treat one benchmark run as the answer, but that is not how benchmarking works. Results vary, especially on short runs, so I had to think about repeatability, scenario design, and what a useful baseline actually looks like. That changed the project from just building features to building a system I could evaluate with some discipline.</p><h3>How I validated it</h3><p>I did not want this to be the kind of systems project that only works in a README. I tested it at multiple levels so I could validate both individual components and the full request path.</p><p>At the code level, I added unit tests around routing, balancing, health state, config validation, upstream behavior, and telemetry. That helped lock down the smaller pieces and made it easier to change internals without breaking core assumptions.</p><p>I also added integration and black-box tests that start the real server and send HTTP traffic through it. One of the tests I like most checks graceful shutdown against a live in-flight request. That matters because shutdown behavior is easy to hand-wave and surprisingly easy to get wrong.</p><pre>#[tokio::test]<br>async fn drains_in_flight_request_during_graceful_shutdown() {<br>    let backend = spawn_slow_upstream(<br>        &quot;drained-backend&quot;,<br>        StatusCode::OK,<br>        Duration::from_millis(100),<br>    )<br>    .await;<br><br>    let (shutdown_tx, shutdown_rx) = oneshot::channel::&lt;()&gt;();<br><br>    let task = tokio::spawn(async move {<br>        let _ = server::run_with_shutdown(config, async move {<br>            let _ = shutdown_rx.await;<br>        })<br>        .await;<br>    });<br><br>    let request_task = tokio::spawn(async move {<br>        get(&amp;base_url, &quot;/api/users&quot;).await<br>    });<br><br>    sleep(Duration::from_millis(20)).await;<br>    let _ = shutdown_tx.send(());<br><br>    let response = timeout(Duration::from_secs(1), request_task).await.unwrap().unwrap();<br>    assert_eq!(response.status, StatusCode::OK);<br>    assert_eq!(response.body, &quot;drained-backend&quot;);<br>}</pre><p>Tests like that gave me more confidence than a basic happy-path check. They forced me to verify behavior at the exact boundary where production systems usually get exposed.</p><p>For performance validation, I built a benchmark workflow around the live proxy using wrk. Instead of measuring tiny internal functions, I measured the real system under healthy traffic, larger responses, retries, and uploads. I also repeated runs to get a more credible baseline, because one benchmark number on its own is not very useful.</p><p>That combination gave me something I trust more than a feature checklist. It gave me evidence that the system behaves the way I intended under both normal and stressed conditions.</p><h3>What I learned</h3><p>The biggest thing I learned is that systems work is mostly about edge cases, not the happy path. The basic request-forwarding flow is not the hard part. The hard part is deciding what the system should do when something is slow, partial, unhealthy, or inconsistent, and then making that behavior observable and predictable.</p><p>I also learned that performance work is easy to talk about and harder to do properly. It is not enough to say something is fast. You need a benchmark that reflects the real request path, a stable enough setup to compare runs, and enough discipline not to overread one good number. Building the benchmark harness was part of the engineering work, not something I tacked on at the end.</p><p>Another lesson was how much operational thinking changes the way you build software. Once you care about graceful shutdown, metrics, retries, backend health, and failure classification, the design gets sharper. You start asking better questions about what the system guarantees, what it exposes, and how it behaves when conditions are bad rather than ideal.</p><p>More than anything, this project pushed me to think in terms of behavior under load instead of just correctness in isolation. That shift made me feel closer to the kind of engineering work I want to keep doing.</p><h3>What this says about me</h3><p>I like building systems where correctness, performance, and failure handling all matter at the same time. This project reflects the kind of work I am drawn to: backend and infrastructure problems where the interesting part is not just making something work, but making it behave well under pressure.</p><p>It also shows how I approach engineering. I like understanding the underlying mechanics, not just using abstractions without questioning them. When I build something, I want to know how it fails, how it recovers, how it is measured, and how confident I should be in its behavior.</p><p>I am also comfortable moving across implementation, debugging, testing, benchmarking, and documentation without treating those as separate concerns. For me, the value is in taking an idea all the way from concept to something that can be reasoned about, tested, and improved with evidence.</p><p>If you work on backend, infrastructure, platform, or systems problems, this is the kind of engineering work I want to keep doing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40284d4c0dca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built a booking system for Newsletter Ads. Here’s every decision I made.]]></title>
            <link>https://medium.com/@judemiracle/i-built-a-booking-system-for-newsletter-ads-heres-every-decision-i-made-f0e25076a8e9?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0e25076a8e9</guid>
            <category><![CDATA[building-in-public]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 14:33:15 GMT</pubDate>
            <atom:updated>2026-02-28T21:16:42.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*E5EUR7dD4npWfPUr.png" /></figure><blockquote><em>I created the booking flow today. This marks the shift of Adsloty from being just a backend project to becoming a real product.</em></blockquote><p>In my last two posts, I talked about important but hidden features like authentication and payments. While these are necessary, they aren’t what draws people to the platform.</p><p>The booking flow is different. This is what users will actually engage with. It’s the process a sponsor goes through to find a newsletter, choose a date, submit their ad, and make a payment. It’s also the experience for a writer when a new booking request arrives in their dashboard, complete with an AI analysis.</p><p>If this experience is complicated, then nothing else matters.</p><h3>What I was aiming for</h3><p>I wanted booking an ad slot to be as easy as booking a flight. You browse, choose, pay, and you’re done. It shouldn’t feel like filling out a loan application or sending a cold email and waiting three days for a reply.</p><p>Adsloty aims to remove the hassle between deciding to sponsor a newsletter and completing the booking. Each extra step, unnecessary form field, or promise of “we’ll get back to you” makes it easier for someone to leave the page.</p><p>I designed the process for speed and clarity.</p><h3>The sponsor’s experience</h3><p>Here’s what sponsors see, step by step:</p><p>First, they discover. Sponsors look through newsletters grouped by topic-like tech, finance, wellness, or the creator economy-that match their products. Each listing shows key details: the number of subscribers, average open rates, cost per slot, and available dates.</p><p>No vanity metrics and no vague pricing. Everything is clear and easy to understand. A sponsor should be able to evaluate a newsletter in under 30 seconds.</p><p>Next is the booking form. After choosing a newsletter, the sponsor selects an available date and fills in their ad details: title, description, call-to-action text, link, and an optional image. That’s all they need to do.</p><p>I spent a lot of time deciding which fields to make required. My first version had twelve fields. I cut it down to six. Each field I removed was something I thought was nice to have but would slow people down. You can ask for more information later, but you can’t win back a user who left because the form felt like homework.</p><p>First, payment is easy. With one click, the sponsor opens Stripe Checkout. They see exactly what they’re paying, confirm the payment, and that’s it. No need to enter card details on my site. I don’t have to maintain or secure a custom payment form. Stripe’s checkout takes care of everything-this includes PCI compliance, 3D Secure, Apple Pay, and Google Pay. I receive a notification when the payment is confirmed.</p><p>The whole process from browsing newsletters to confirming payment can take less than two minutes. That was the goal.</p><blockquote><em>In the future I plan making it a escrow based system.</em></blockquote><h3>The writer’s experience</h3><p>The writer’s dashboard shows a new booking request. It doesn’t just say “someone wants to buy an ad slot.” It provides additional context.</p><p>This is where the AI analysis comes in.</p><p>When a sponsor submits their ad, the backend sends it to Google’s Gemini API along with the newsletter’s audience data. Before the writer even looks at the request, the AI has already scored it.:</p><p>You will receive a fit score between 0 and 100 for your ad. The score is based on tone analysis, clarity rating, and an estimated click range. You will also get three to five specific recommendations.</p><p>You don’t have to wonder if an ad is a good fit. Just open the request to see the score, read the recommendations, and decide whether to approve or reject with one button.</p><p>Initially, I thought about automatically rejecting ads that scored below a certain level. I chose not to do that. The AI is a tool to help, not a barrier. A score of 40 might be just right for a writer starting out who wants to earn money. A score of 90 might still be rejected if the writer doesn’t like the brand. The writer makes the final decision, while the AI provides helpful information.</p><h3>The state machine</h3><p>Here’s where things became more complex.</p><p>A booking is not simply “booked” or “not booked.” It has a process. This process must be clear and organized because money is involved in every step.</p><pre>draft → pending_payment → paid → confirmed → completed → rejected → refunded → expired → cancelled → refunded</pre><p>Let me explain each step:</p><ul><li><strong>Draft.</strong> The sponsor started filling out the form but hasn’t paid yet. They may have gotten distracted or are comparing newsletters. Their booking is still in the system, so they can return to it later.</li><li><strong>Pending payment.</strong> The sponsor clicked “Book now” and was directed to Stripe Checkout. We are waiting for the payment confirmation.</li><li><strong>Paid.</strong> Stripe confirmed the payment. The writer gets notified, and we run an AI analysis. The booking appears in the writer’s dashboard.</li><li><strong>Confirmed.</strong> The writer approved the ad. It is locked in for the scheduled date, and a payout record is created with a “pending” status.</li><li><strong>Completed.</strong> The publication date has passed. Our system marks it as complete and processes the payout to the writer.</li><li><strong>Rejected.</strong> The writer declined the ad. The sponsor receives a full refund, and the payout record is canceled.</li><li><strong>Expired.</strong> The writer did not respond within the time limit, so we automatically refund the sponsor.</li><li><strong>Cancelled.</strong> The sponsor canceled the booking before the writer confirmed it. We process a refund.</li></ul><p>Each of these steps triggers different actions-like updating the database, sending email notifications, or processing payouts and refunds. There are rules about which steps can follow others. For example, you can’t go from “completed” back to “draft,” and you can’t reject a booking that has already been refunded.</p><p>I handle this in the backend. Every status update first checks with can_transition_to. If the transition isn&#39;t valid, it shows an error. There are no exceptions. This one function has likely prevented more bugs than anything else I&#39;ve written for this project.</p><h3>Notifications at every step</h3><p>Nobody should be confused about their booking status. So, I created email notifications for each important update:</p><ul><li>When the sponsor pays, they get an email: “Your booking is confirmed, waiting for writer approval.”</li><li>When a writer receives a new request, they get: “New ad request for [newsletter name] — review it now.”</li><li>When the writer approves the ad, the sponsor gets: “Your ad has been approved for [date].”</li><li>If the writer rejects it, the sponsor gets: “Your ad wasn’t approved — a refund is on its way.”</li><li>After the ad completes, the writer gets: “Payout of $X is being processed.”</li><li>When the payout arrives, the writer gets: “You’ve been paid.”</li></ul><p>The emails are straightforward. They explain what happened and what will happen next, without any sales language. When it comes to money, being clear is more important than being clever.</p><h3>The embeddable widget</h3><p>I built something this week that I’m really excited about: writers can now add a booking widget directly to their newsletter website.</p><p>It creates a button that sponsors can click to view the writer’s available dates and pricing. They can start the booking process directly from the writer’s site without needing to visit Adsloty. This makes the writer’s website a sales page for their ads.</p><p>Writers can customize the colors, button text, and placement to ensure it fits seamlessly with their site. I am also tracking impressions, clicks, and conversion rates for each widget, so writers can see how many visitors become sponsors.</p><h3>What’s still rough</h3><p>I won’t pretend it’s perfect. The discovery page needs better filters and search options. The user interface works, but it still doesn’t feel great. The AI analysis can take a few seconds, so I need to add proper loading states instead of the spinner I added in a hurry.</p><p>My analytics are basic. I’m tracking numbers, but I need to present them better. Writers should be able to see trends, compare months, and know which topics generate the most revenue. That’s in the works.</p><h3>But the core loop works</h3><p>A sponsor can find a newsletter, book a slot, pay, and submit their ad. A writer can review the request using AI analysis, approve it, and get paid automatically after the publication date.</p><p>This is the core of the product. Everything else is just added features.</p><p>If you run a newsletter and want to try this during the beta phase-or if you are a brand that has found sponsoring newsletters difficult-I would really like to know what you think. What would make this more useful for you?</p><p>More updates soon.</p><p><em>Originally published at </em><a href="https://dev.to/miraclejudeiv/i-built-a-booking-system-for-newsletter-ads-heres-every-decision-i-made-1k6n"><em>https://dev.to</em></a><em> on February 27, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0e25076a8e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I integrated Stripe into a two-sided marketplace. Here’s what actually happens]]></title>
            <link>https://medium.com/@judemiracle/i-integrated-stripe-into-a-two-sided-marketplace-heres-what-actually-happens-92631e624033?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/92631e624033</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[building-in-public]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 12:51:59 GMT</pubDate>
            <atom:updated>2026-02-27T15:10:47.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*H9ChAzHNpQpzTrmU.png" /></figure><blockquote><em>I spent all day making money move. It was harder than I expected.</em></blockquote><p>At some point in building a marketplace, you shift from adding features to setting up the behind-the-scenes systems. This includes payment processing. This work often goes unnoticed and rarely gets shared online, but if mistakes happen, real people can lose real money.</p><p>That’s how I spent my entire week.</p><p>Adsloty is a marketplace where sponsors pay to reserve ad slots in newsletters. Writers earn money after the ads run. While this sounds simple, there is a complex system behind it that ensures every penny goes to the right place at the right time.</p><p>Here’s what I built, what went wrong, and what I learned.</p><h3>Stripe Connect: paying writers directly</h3><p>The first decision was about how writers get paid. I could collect all the money myself and manually send payouts. However, that would be a nightmare to handle and a legal headache right from the start.</p><p>Instead, I chose Stripe Connect. Each writer links their own Stripe account to Adsloty. When a sponsor books an ad slot, the payment goes through our platform. Stripe automatically splits the payment: the writer’s share goes to their connected account, and the platform fee stays with me.</p><p>The onboarding flow looks like this:</p><p>The writer clicks a link, enters their banking details on Stripe’s secure page, and then returns. I never handle their bank information. Stripe takes care of identity checks and verification. That alone makes the processing fee worth it.</p><p>However, I did not expect that onboarding would not always be quick. Sometimes, Stripe needs to verify identities, which can take hours or even days. So, I had to keep track of the onboarding status and stop writers from accepting paid bookings until their accounts are fully active.</p><h3>The payment flow</h3><p>When a sponsor wants to book an ad slot, here’s what happens:</p><ol><li>The sponsor fills in the ad details and selects a date.</li><li>The frontend creates a checkout session through the backend.</li><li>The backend calculates the platform fee and sets up a Stripe Checkout Session.</li><li>The sponsor pays on Stripe’s hosted checkout page.</li><li>Stripe sends a message to confirm the payment.</li><li>The backend creates the booking and adds a pending payout record.</li><li>After the publication date, the payout goes to the writer.</li></ol><p>The platform charges a 10% fee. I carefully considered this amount. If it’s too high, writers will leave. If it’s too low, the business won’t be sustainable. I believe 10% is fair for the services the platform offers, including discovery, booking management, AI analysis, and payment handling. During the beta phase, I will not charge this fee at all for the first three months to attract early users.</p><p>I made the fee adjustable using an environment variable. I’ve noticed that hardcoding financial details is a common mistake in many projects. When running a promotion or changing prices, you don’t want to have to redeploy.</p><h3>Webhooks</h3><p>Stripe does not simply tell your frontend that a payment succeeded and leave it at that. The actual confirmation comes through webhooks. Stripe sends an HTTP request to your backend with the event details. This is the accurate source of information, not the redirect URL or the frontend callback. It’s the webhook that matters.</p><p>However, webhooks can arrive late, arrive twice, or not arrive at all (and then retry). Your code needs to handle all these scenarios.</p><p>Here are a few important points to keep in mind:</p><p>First, verify signatures. Every webhook from Stripe is signed. If you skip this step, anyone could send fake “payment succeeded” messages to your endpoint and get free products. In a marketplace that handles money, this check is essential.</p><p>Second, handle events only once. I store every webhook event ID in the database before processing it. If Stripe sends the same event again, I check the ID, see it’s already been handled, and return a 200 response without doing anything. This prevents issues like processing the same payment twice or creating duplicate bookings.</p><p>Third, save the original event before I process it. If my processing fails partway through, I still have the event saved. I can replay it, debug it, or solve any issues manually. When money is involved, it’s crucial to have a clear record.</p><h3>The payout lifecycle</h3><p>This is where it gets interesting. A payout isn’t just about sending money to the writer. It has a process that involves several stages.</p><pre>pending → processing → completed → failed</pre><p>When a sponsor makes a payment, we create a payout record that has a status of “pending.” This record stays in that state until the ad’s publication date arrives. After that date, a background job processes it.</p><p>Why can’t we pay writers right away when the sponsor pays? It’s because the ad hasn’t run yet. If the writer doesn’t publish the ad or the sponsor asks for a refund before the date, we need to cancel the payout. Once we send the money, getting it back can be very difficult.</p><h3>Edge cases</h3><p>The happy path is straightforward: the sponsor pays, the ad runs, and the writer gets paid. But then reality hits:</p><p>Sometimes, sponsors change their minds before the ad is published. When that happens, I need to refund the entire amount, cancel the pending payment, and update the booking status. I must do all of this in one transaction so everything stays consistent.</p><p><em>Failed Transfers.</em> Sometimes, Stripe cannot send money to a writer’s account. This might happen if their bank rejects the transfer or if there are issues with their Stripe account. When this occurs, the payout is marked as failed. I must inform the writer so they can update their account details and try again.</p><p><em>Disputes.</em> A sponsor’s bank may start a chargeback. This is the worst-case scenario. The money gets taken back, and I need to handle it carefully. This involves updating the booking, notifying both parties, and possibly flagging the account.</p><p>Each of these situations requires its own solution, state updates, and notifications. It may not be exciting work, but if we skip any steps, someone will eventually lose money and trust.</p><h3>What I learned this week</h3><p>Payments in a marketplace are not just a feature; they are the foundation of the system. You can’t simply add them in later-they impact everything. This includes the booking flow, the notification system, the user dashboard, the admin tools, error handling, and background jobs. Everything is connected.</p><p>If I could give myself one piece of advice, it would be to start with the payment flow first. Design the booking process around how money moves, not the other way around. I followed a similar path, but I had to go back and make changes because I had incorrect assumptions about how payments work.</p><p>Additionally, read Stripe’s documentation thoroughly. Don’t just skim the quickstart guide. Pay attention to the webhook best practices, the Connect account lifecycle, and the dispute handling guide. It may be dense, but every page will save you a lot of time later when you need to debug issues.</p><h3>What’s next</h3><p>The booking process is where a sponsor selects a newsletter, picks a date, writes their advertisement, and makes a payment. This is also where our AI fit scoring comes in, analyzing the advertisement in relation to the newsletter’s audience before the writer sees it.</p><p>This is what makes Adsloty unique. Payments are the base, but the booking experience is the core product.</p><p>More soon</p><p><em>Originally published at </em><a href="https://dev.to/miraclejudeiv/i-integrated-stripe-into-a-two-sided-marketplace-heres-what-actually-happens-2mpb"><em>https://dev.to</em></a><em> on February 23, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92631e624033" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building in public #2: The auth rabbit hole]]></title>
            <link>https://medium.com/@judemiracle/building-in-public-2-the-auth-rabbit-hole-52f8add52990?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f8add52990</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[build-in-public]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 08:00:49 GMT</pubDate>
            <atom:updated>2026-02-23T12:43:35.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-Ih6OzSDCPCJlpdy.png" /></figure><blockquote><em>I spent a week on authentication. It nearly broke me.</em></blockquote><p>Last time, I explained what Adsloty is and why I’m creating it. This time, I want to talk about something less exciting: authentication.</p><p>I knew handling authentication wouldn’t be easy. This isn’t just a simple blog or a to-do app. Adsloty deals with real money. Sponsors pay for ad slots, and writers receive payments. When money flows through your platform, the phrase “it works on my machine” isn’t enough. You must consider what happens when someone tries to break in.</p><p>I learned this lesson the hard way. Here’s what went wrong and how I fixed it.</p><h3>The brute force problem</h3><p>My first login setup was very basic. It included an endpoint that accepts an email and password, checks if they match, and returns a token. There were no limits or tracking, which meant someone could easily try many password guesses without any barriers.</p><p>To fix this, I made some changes to the system. I added a counter in the database to track failed login attempts. Each incorrect password increases this counter. After five failed attempts, the account locks for 30 minutes. If the user logs in successfully, the counter resets.</p><p>I also ensured users could easily regain access. If they reset their password, the account unlocks right away. Locking users out of their accounts without a way to recover is a sure way to lose them.</p><p>This solution isn’t complicated and doesn’t include advanced features like machine learning to find suspicious activity. However, it works, and I could implement it in a day. I can always add more sophisticated features later.</p><h3>Token theft and the rotation fix</h3><p>This one scared me more.</p><p>I originally used refresh tokens that lasted for 30 days. When you log in, you will receive a short-lived access token and a long-lived refresh token. You used the refresh token to get new access tokens when the old ones expired. This is standard practice.</p><p>The problem was that if someone stole the refresh token through a hacked device or a leaked log, for example, they could have access for 30 days without you knowing.</p><p>The solution was token rotation. Now, every time someone uses a refresh token, it gets canceled right away, and a new one is issued. The old token becomes invalid as soon as it is exchanged. So, if an attacker steals a token and tries to use it after the real user has already used it, it will fail. The time an attacker can use a stolen token shrinks from 30 days down to the time it takes the real user to make their next request.</p><p>Three steps. Use it, kill it, replace it. If an attacker replays the old token, step one fails because step two already ran.</p><p>It made the token process more complex, with more database updates and more possible issues to handle. But for a platform that deals with payments, it’s essential.</p><h3>The cookie bug that only existed in production</h3><p>This situation was frustrating because everything worked well on my local machine.</p><p>I store authentication tokens in HttpOnly cookies. For production, these cookies must have the Secure flag so they are only sent over HTTPS. That makes sense. However, I didn&#39;t realize at first that a cookie marked Secure won&#39;t be set on localhost when using plain HTTP.</p><p>After I deployed and tested the login, it just didn’t work. There were no errors. The server set the cookie, but the browser ignored it silently. I spent too much time looking at the network tabs before I figured out what was wrong.</p><p>The solution was to adjust the cookie settings based on the environment. In production, I use Secure, HttpOnly, and SameSite=Lax. In development, I use the same settings but without the Secure flag. It took only a few lines of code to fix, but it took hours to find the problem. It was the kind of bug that makes you doubt your career choices.</p><p>And then, where it’s called:</p><p>One boolean. That’s all it took. But finding out I needed it cost me an afternoon.</p><h3>Two users, two completely different flows</h3><p>Adsloty has two types of users: writers and sponsors. They use the same login form, but the process is very different for each.</p><p>Writers need to provide details about their newsletter, like its name, URL, and subscriber count. They must also complete an onboarding process before they can list ad slots. Sponsors only need to give their company name to get started.</p><p>At first, I tried to use a single registration endpoint with an if statement to handle both types. This approach became messy within an hour. There were different validation rules, different database tables, and different onboarding steps. Trying to put everything into one handler made the code hard to read.</p><p>So, I separated the registration into two endpoints, one for writers and one for sponsors. I created different profile tables in the database. The JWT includes the user’s role, and every protected route checks if the user is logged in and allowed to access that area. A sponsor cannot enter the writer’s dashboard, and a writer cannot access campaign management.</p><p>And the JWT generation that carries the role:</p><p>This method requires more code, but it keeps each path clear and easy to understand. If something goes wrong in the writer registration process, I know exactly where to find the issue.</p><h3>Logging everything</h3><p>One decision I made early on that I’m thankful for is logging every authentication event. This includes each successful login, every failed attempt, every token refresh, every email verification, and every password reset. All this information goes into an auth_events table, which includes timestamps, user IDs, IP addresses, and whether each event succeeded or failed.</p><p>Every auth function ends with one of these. It’s repetitive to write, but when someone emails you saying, ‘I can’t log in,’ you’ll be glad you have it.</p><p>I haven’t needed this data for a real incident yet. But when you’re handling other people’s money, saying “I don’t know what happened” is not acceptable. When something goes wrong, and it always does, I want to know exactly what happened and when.</p><h3>What I’d tell someone building auth for a payments app</h3><p>Don’t underestimate this task. It’s not something you can do in a weekend. Every shortcut you take will likely cause problems when real money is involved.</p><p>Lock accounts after failed login attempts. Rotate your tokens regularly. Make your cookie configuration aware of the environment from the start. Keep user types separate instead of complicating things with conditionals. Also, log more information than you think you need.</p><p>None of this is new or exciting. But making sure you do it correctly, in the right order, and without any gaps is where you will spend your time.</p><p>Next time, I’ll probably write about integrating Stripe Connect and the challenges of managing webhooks in a two-sided marketplace. That has been its own adventure.</p><p>Until then.</p><p><em>Originally published at </em><a href="https://dev.to/miraclejudeiv/building-in-public-2-the-auth-rabbit-hole-436i"><em>https://dev.to</em></a><em> on February 21, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f8add52990" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building in public: Adsloty, a Newsletter Ad Marketplace]]></title>
            <link>https://medium.com/@judemiracle/building-in-public-adsloty-a-newsletter-ad-marketplace-64d8800ff213?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/64d8800ff213</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[building-in-public]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 11:00:34 GMT</pubDate>
            <atom:updated>2026-02-20T13:16:52.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*aJe6Z29pfZQKvfFN.png" /></figure><blockquote><em>I’m building Adsloty. Here’s why.</em></blockquote><p>If you run a newsletter, you’ve probably dealt with this: a brand reaches out wanting to sponsor an issue. Cool. Then starts the back-and-forth. Pricing negotiations over email. Figuring out dates. Chasing invoices. Copy-pasting ad copy into your template manually. It works, but barely.</p><p>And if you’re on the other side (sponsor), a brand trying to get in front of a newsletter audience, it’s just as painful. You’re DMing creators, waiting days for replies, comparing pricing across spreadsheets, and hoping the audience actually fits your product.</p><p>I kept seeing this friction and thought: there has to be a better way.</p><p>So I started building Adsloty.</p><h3>What it is</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*i330KgblwVyGpZEk.png" /></figure><p>Adsloty is a self-service marketplace where newsletter writers list their ad slots and sponsors book them directly. No emails back and forth. No awkward pricing conversations. Writers set their price, sponsors browse and book, and the platform handles payments and payouts.</p><p>Think of it like Calendly meets Gumroad, but specifically for newsletter ads.</p><p>The part I’m most excited about: when a sponsor submits an ad, it gets analyzed by AI before the writer even sees it. It scores how well the ad fits the newsletter’s audience, checks the tone, rates the clarity of the copy, and gives the writer an estimated click range. So instead of guessing whether an ad is a good fit, you get actual data to help you decide.</p><h3>Why I’m building it</h3><p>Honestly? Because I wanted it to exist.</p><p>The newsletter space is booming. More people are starting newsletters, more brands want to reach those audiences, but the infrastructure to connect them is still mostly manual. The tools that exist are either too enterprise (built for massive publishers) or too scrappy (a Typeform and a Stripe link).</p><p>I wanted something in the middle. Something a solo newsletter creator could set up in minutes, embed on their site, and start earning from — without hiring a sales team or building a media kit.</p><p>And I wanted to build it myself. Not because I have to, but because I genuinely enjoy solving this kind of problem end to end.</p><h3>The tech stack</h3><p>This is the part some of you are here for, so let me break it down.</p><p>The backend is Rust, running on Axum. I know, I know Rust for a web app might seem like overkill, probably. But I’m learning a lot, and the performance headroom means I won’t need to rewrite anything when traffic picks up. But I’ve grown to love writing Rust. The type system catches so many bugs before they even make it to runtime. SQLx gives me compile-time checked SQL queries against Postgres, which means if my query doesn’t match the schema, it won’t even compile. That alone has saved me hours of debugging.</p><p>The frontend is Next.js with the App Router, React 19, and Tailwind CSS. State management is Zustand for global state and TanStack Query for server state. Forms are handled with React Hook Form and Zod for validation. Nothing groundbreaking here, I picked tools that let me move fast without fighting the framework.</p><p>For payments, it’s Stripe all the way. Checkout Sessions for sponsors, Connect for paying out writers. The platform takes a 10% fee on each booking, which is how the business sustains itself. During beta, that fee is waived for the first three months.</p><p>The AI scoring uses Google’s Gemini API. When a sponsor submits an ad, the backend sends the ad copy along with the newsletter’s audience data to Gemini and gets back a structured analysis: fit score, tone, clarity, estimated clicks, and recommendations. It’s not meant to replace the writer’s judgment — it’s meant to give them a head start.</p><p>For everything else: Cloudinary for image hosting, Sentry for error tracking on both frontend and backend, Argon2 for password hashing, JWT with refresh token rotation for auth, and Governor for rate limiting.</p><p>The database is Postgres. Nothing fancy. Just well-structured tables, proper indexes, and views for the dashboard queries.</p><p>I will use this project to improve my skills in DevOps by deploying and managing it with Kubernetes. This involves:</p><ul><li>Containerizing services with Docker and- Deploying both backend and frontend in a Kubernetes cluster</li><li>Managing settings with ConfigMaps and Secrets</li><li>Setting up Services and Ingress</li><li>Managing scaling and rolling updates</li><li>Ensuring observability and health checks</li></ul><p>The aim is to treat this as a production system, not just an application.</p><p>I’m going to keep building in public. I’ll share what’s working, what’s breaking, what decisions I’m making, and why. Not the curated everything is going great version. The real version.</p><p>If you’re running a newsletter and want to try it out when it launches, or if you’re a brand looking for a better way to sponsor newsletters, I’d love to hear from you.</p><p>More soon.</p><p><em>Originally published at </em><a href="https://dev.to/miraclejudeiv/building-in-public-adsloty-a-newsletter-ad-marketplace-2nh8"><em>https://dev.to</em></a><em> on February 19, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64d8800ff213" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing React hydration errors when using Zustand persist with useSyncExternalStore]]></title>
            <link>https://medium.com/@judemiracle/fixing-react-hydration-errors-when-using-zustand-persist-with-usesyncexternalstore-b6d7a40f2623?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d7a40f2623</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[hydration]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 21:32:48 GMT</pubDate>
            <atom:updated>2025-11-14T22:30:43.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pMXb0qlqlZIAN-mp" /><figcaption>Photo by <a href="https://unsplash.com/@shoperpl?utm_source=medium&amp;utm_medium=referral">Shoper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Last week, I spent three hours debugging a hydration error that had me questioning my entire understanding of React. The kind of error that makes you wonder if you should’ve just become a carpenter instead.</p><p>But here’s the thing — once I figured it out, it all made perfect sense. And I’m willing to bet you’re dealing with the same issue right now. So let me save you those three hours.</p><h4>Here’s what happened</h4><p>I was building a pretty standard e-commerce site. Nothing fancy — products, filters, and a shopping cart. You know, the usual stuff. I used Zustand for state management because it’s cleaner than Redux, and I added the persist middleware so users wouldn’t lose their cart when they refreshed the page. Smart, right?</p><p>Wrong. Well, not wrong exactly. But I was about to learn something new.</p><p>Everything looked perfect in development. The cart worked, items persisted, life was good. Then I deployed to production and opened the console, and there it was:</p><pre><br>Hydration failed because the server rendered HTML didn’t match the client.<br></pre><p>Fantastic.</p><h4>The code that broke everything</h4><p>Here’s what my header component looked like. Pretty simple stuff:</p><pre>&quot;use client&quot;;<br>import { useCartStore } from &quot;@/lib/stores/cartStores&quot;;<br>import { Button } from &quot;@/components/ui/button&quot;;<br>import { ShoppingCart } from &quot;lucide-react&quot;;<br>import { Badge } from &quot;@/components/ui/badge&quot;;<br><br>export function Header() {<br>  const totalItems = useCartStore((state) =&gt; state.getTotalItems());<br>  return (<br>    &lt;header&gt;<br>       <br>      &lt;Button variant=&quot;ghost&quot; size=&quot;icon&quot; className=&quot;relative&quot;&gt;<br>         &lt;ShoppingCart className=&quot;w-5 h-5&quot; /&gt; <br>        {totalItems &gt; 0 &amp;&amp; (<br>          &lt;Badge className=&quot;absolute -top-1 -right-1&quot;&gt;<br>             {totalItems &gt; 99 ? &quot;99+&quot; : totalItems} <br>          &lt;/Badge&gt;<br>        )}<br>         <br>      &lt;/Button&gt;<br>       <br>    &lt;/header&gt;<br>  );<br>}</pre><p>Just a cart button with a little badge showing how many items you’ve added. Nothing crazy.</p><p>And here’s my Zustand store:</p><pre>import { create } from &quot;zustand&quot;;<br>import { persist } from &quot;zustand/middleware&quot;;<br><br>export const useCartStore = create(<br>  persist(<br>    (set, get) =&gt; ({<br>      items: [],<br>      addItem: (product, quantity = 1) =&gt; {<br>        // … handles adding items<br>      },<br>      getTotalItems: () =&gt;<br>        get().items.reduce((sum, item) =&gt; sum + item.quantity, 0),<br>    }),<br>    {<br>      name: &quot;cart-storage&quot;, // saves to localStorage<br>    },<br>  ),<br>);</pre><p>Again, totally normal. So why was React having a meltdown?</p><h4>What actually went wrong</h4><p>Okay, so here’s what was happening, and honestly, once you understand it, it’s kind of obvious. But when you’re in the thick of it at 11 PM, nothing is obvious.</p><p>On the server:</p><ul><li>Next.js renders your component</li><li>The Zustand store initializes with an empty cart (no localStorage on the server, obviously)</li><li>getTotalItems() returns 0</li><li>The badge doesn’t render because totalItems &gt; 0 is false</li><li>Server sends HTML with just a button and cart icon</li></ul><p>On the client:</p><ul><li>The browser receives that HTML</li><li>React starts hydrating</li><li>Zustand’s persistmiddleware wakes up and goes “oh hey, let me check localStorage”</li><li>Finds your saved cart with 3 items in it</li><li>getTotalItems() now returns 3</li><li>React tries to render the badge</li><li>React looks at the server HTML and goes, “wait, where’s this badge supposed to go? This doesn’t match!”</li></ul><p>And that’s your hydration error. The server said “no badge,” but the client said “definitely badge.”</p><h4>My first “fix” (don’t do this)</h4><p>Like any reasonable developer who just wants to go to bed, I Googled “prevent render until mounted React” and found the classic pattern:</p><pre>export function Header() {<br>  const [mounted, setMounted] = useState(false);<br>  const totalItems = useCartStore((state) =&gt; state.getTotalItems());<br><br>  useEffect(() =&gt; {<br>    setMounted(true);<br>  }, []);<br>  return (<br>    &lt;header&gt;<br>       <br>      &lt;Button variant=&quot;ghost&quot; size=&quot;icon&quot;&gt;<br>         &lt;ShoppingCart className=&quot;w-5 h-5&quot; /&gt; <br>        {mounted &amp;&amp; totalItems &gt; 0 &amp;&amp; &lt;Badge&gt;{totalItems}&lt;/Badge&gt;} <br>      &lt;/Button&gt;<br>       <br>    &lt;/header&gt;<br>  );<br>}</pre><p>“Perfect!” I thought. “Now the badge won’t render until we’re on the client!”</p><p>And it worked! The hydration error was gone. I did a little victory dance. I was about to commit the code.</p><p>Then ESLint hit me with this:</p><pre>Error: Calling setState synchronously within an effect can trigger cascading renders.<br>Effects are intended to synchronize state between React and external systems…<br>Calling setState synchronously within an effect body causes cascading renders <br>that can hurt performance, and is not recommended.</pre><p>Excuse me?</p><h4>Why React wasn’t happy</h4><p>Turns out, what I did was the equivalent of asking React to do extra work for no good reason. Here’s what happens with that mounted pattern:</p><ol><li>Component renders with mounted: false, badge hidden</li><li>The browser paints the screen</li><li>useEffect runs immediately</li><li>Sets mounted: true</li><li>This triggers another render immediately</li><li>The browser has to repaint</li></ol><p>React is basically saying, “Dude, why are you making me render twice? That’s what effects are NOT for.”</p><p>Effects are supposed to sync with external systems (like subscribing to WebSocket, or setting up event listeners), not to immediately trigger another render. It’s like asking someone to go to the store, come back, then immediately go back to the same store. Inefficient.</p><p>And I get it now. This pattern technically works, but it’s fighting against React instead of working with it.</p><h4>The actual solution (useSyncExternalStore)</h4><p>So at this point, I’m frustrated, tired, and seriously considering that carpentry career. But then I stumbled across useSyncExternalStore and everything clicked.</p><p>This hook was literally designed for exactly my situation. It was added in React 18 specifically to handle external stores (like Zustand, Redux, or even browser APIs) that might have different values on the server vs. the client.</p><p>Here’s what the fixed code looks like:</p><pre>&quot;use client&quot;;<br>import { useSyncExternalStore } from &quot;react&quot;;<br>import { useCartStore } from &quot;@/lib/stores/cartStores&quot;;<br>import { Button } from &quot;@/components/ui/button&quot;;<br>import { ShoppingCart } from &quot;lucide-react&quot;;<br>import { Badge } from &quot;@/components/ui/badge&quot;;<br><br>export function Header() {<br>  const totalItems = useSyncExternalStore(<br>    useCartStore.subscribe,<br>    () =&gt; useCartStore.getState().getTotalItems(),<br>    () =&gt; 0,<br>  );<br>  return (<br>    &lt;header&gt;<br>       <br>      &lt;Button variant=&quot;ghost&quot; size=&quot;icon&quot; className=&quot;relative&quot;&gt;<br>         &lt;ShoppingCart className=&quot;w-5 h-5&quot; /&gt; <br>        {totalItems &gt; 0 &amp;&amp; (<br>          &lt;Badge className=&quot;absolute -top-1 -right-1&quot;&gt;<br>             {totalItems &gt; 99 ? &quot;99+&quot; : totalItems} <br>          &lt;/Badge&gt;<br>        )}<br>         <br>      &lt;/Button&gt;<br>       <br>    &lt;/header&gt;<br>  );<br>}</pre><p>That’s it. No useEffect. No mounted state. No ESLint warnings. No hydration errors.</p><h4>Breaking It down</h4><p>useSyncExternalStore takes three arguments, and each one has a purpose:</p><p><strong>First argument: The subscribe function</strong></p><pre>useCartStore.subscribe</pre><p>This is how React subscribes to changes in your store. Zustand gives you this for free. When someone adds an item to the cart, this function makes sure React knows to re-render. You don’t have to write this yourself — Zustand handles it.</p><p><strong>Second argument: Get the client value</strong></p><pre>() =&gt; useCartStore.getState().getTotalItems()</pre><p>This is what the value actually is on the client. After the page loads, after localStorage has been read, this is the real number of items in the cart. This is what users see.</p><p><strong>Third argument: Get the server value</strong></p><pre>() =&gt; 0</pre><p>This is the key to the whole thing. This tells React “when you’re rendering on the server, the cart count is zero.”</p><p>And that’s exactly what the server rendered! No cart data, no localStorage, no items. Zero.</p><h4>Why this works (the magic part)</h4><p>Here’s what blew my mind when I finally understood it:</p><p>During server-side rendering:</p><ul><li>React calls that third function: () =&gt; 0</li><li>Gets 0 back</li><li>Badge doesn’t render (because 0 &gt; 0 is false)</li><li>Sends HTML with no badge</li><li>Everything matches</li></ul><p>During hydration of the client:</p><ul><li>React calls the second function: () =&gt; useCartStore.getState().getTotalItems()</li><li>Zustand reads localStorage</li><li>Gets 3 back</li><li>React goes “oh, the server value was different from the client value”</li><li>But here’s the magic: <strong>React expects this</strong></li><li>We explicitly told React “server has 0, client might have something else”</li><li>React handles the transition smoothly</li><li>No hydration error!</li></ul><p>The difference between this and my broken code is that with useSyncExternalStore, I’m not trying to hide the mismatch from React. I’m telling React upfront: “Hey, these values are going to be different, and that’s okay.”</p><p>React appreciates the honesty.</p><h4>When you’ll need this</h4><p>After going through this whole ordeal, I started noticing situations where this pattern applies everywhere. You need useSyncExternalStore whenever you have data that’s different on the server vs. the client.</p><p>Shopping carts (like mine)</p><ul><li>Server: empty cart</li><li>Client: saved cart from localStorage</li></ul><p><strong>User authentication</strong></p><pre>const isLoggedIn = useSyncExternalStore(<br>  useAuthStore.subscribe,<br>  () =&gt; useAuthStore.getState().isLoggedIn,<br>  () =&gt; false, // assume logged out on server<br>);</pre><p><strong>Theme preferences</strong></p><pre>const theme = useSyncExternalStore(<br>  useThemeStore.subscribe,<br>  () =&gt; useThemeStore.getState().theme,<br>  () =&gt; &quot;light&quot;, // default to light on server<br>);</pre><p><strong>Window size</strong> (for responsive stuff)</p><pre>const windowWidth = useSyncExternalStore(<br>  (callback) =&gt; {<br>    window.addEventListener(&quot;resize&quot;, callback);<br>    return () =&gt; window.removeEventListener(&quot;resize&quot;, callback);<br>  },<br>  () =&gt; window.innerWidth,<br>  () =&gt; 1024, // assume desktop on server<br>);<br></pre><p><strong>Online/offline status</strong></p><pre>const isOnline = useSyncExternalStore(<br>  (callback) =&gt; {<br>    window.addEventListener(&quot;online&quot;, callback);<br>    window.addEventListener(&quot;offline&quot;, callback);<br>    return () =&gt; {<br>      window.removeEventListener(&quot;online&quot;, callback);<br>      window.removeEventListener(&quot;offline&quot;, callback);<br>    };<br>  },<br>  () =&gt; navigator.onLine,<br>  () =&gt; true, // assume online on server<br>);</pre><p>Basically, if it touches localStorage, sessionStorage, or any browser API that doesn’t exist on the server, you probably need this hook.</p><h4>When you DON’T need this</h4><p>Don’t go crazy and use this everywhere. You don’t need it for:</p><p><strong>Regular React state</strong></p><pre>// Just use useState, seriously<br>const [count, setCount] = useState(0);</pre><p><strong>Context values</strong></p><pre>// Context is fine as-is<br>const theme = useContext(ThemeContext);</pre><p><strong>Props</strong></p><pre>// Props are just props<br>function Badge({ count }) {<br>   return &lt;span&gt;{count}&lt;/span&gt;;<br>}</pre><p><strong>Data that’s the same on server and client</strong><br>If you’re loading products via getServerSideProps and they’re the same on both sides, you don’t need this. The whole point is handling when they’re different.</p><h4>The one thing to get right</h4><p>The most important part is picking the right server value (that third argument). It should match what the server actually renders.</p><pre>// Good - server has no cart data<br>const cartCount = useSyncExternalStore(<br>  subscribe,<br>  () =&gt; getCartCount(),<br>  () =&gt; 0,<br>);<br>// Bad - server never renders 99<br>const cartCount = useSyncExternalStore(<br>  subscribe,<br>  () =&gt; getCartCount(),<br>  () =&gt; 99, // why would this be 99 on the server?<br>);</pre><p>Think about it like this: What would this value be if the user had never visited your site before? That’s your server value.</p><h4>A quick word about the flash</h4><p>You might notice the badge appears a split second after the page loads. That’s normal. The server renders no badge, then the client adds it after hydration. It’s fast enough that most users won’t notice.</p><p>If it bothers you, you can:</p><p>Reserve space for it:</p><pre>&lt;div className=&quot;w-5 h-5&quot;&gt;<br> {totalItems &gt; 0 &amp;&amp; &lt;Badge&gt;{totalItems}&lt;/Badge&gt;}<br>&lt;/div&gt;</pre><p>Use a skeleton:</p><pre>{totalItems === undefined ? (<br> &lt;div className=&quot;w-5 h-5 bg-gray-200 animate-pulse rounded-full&quot; /&gt;<br>) : totalItems &gt; 0 ? (<br> &lt;Badge&gt;{totalItems}&lt;/Badge&gt;<br>) : null}</pre><p>But honestly? I just left it. The flash is so quick that trying to fix it might make things worse.</p><h4>What I earned</h4><p>Here’s what this whole experience taught me:</p><ol><li>Hydration errors aren’t random — They’re React protecting you from bugs. When the server HTML doesn’t match the client, something’s actually wrong.</li><li>The “mounted” pattern is a code smell— If you’re using useEffect to set state immediately, you’re probably doing it wrong. There’s usually a better way.</li><li>React 18 has tools for this — useSyncExternalStore exists specifically for external stores. Use it.</li><li>Be explicit about mismatches — Don’t try to hide server/client differences from React. Tell React what’s going on and let it handle it.</li><li>ESLint warnings are your friend — That cascading renders warning saved me from shipping bad code. Listen to the linter.</li></ol><h4>The pattern you’ll actually use</h4><p>Forget all the explanation. Here’s what you’ll copy-paste next time you’re using an external state management library like Zustand/Redux:</p><pre>import { useSyncExternalStore } from &quot;react&quot;;<br>const value = useSyncExternalStore(<br>  yourStore.subscribe,<br>  () =&gt; yourStore.getState().value, // client value<br>  () =&gt; defaultValue, // server value<br>);</pre><p>That’s it. Three lines. No effects, no mounting flags, no hydration errors.</p><h4>One last thing</h4><p>If you’re reading this because you’re debugging a hydration error right now, I feel you. It’s frustrating. But take a step back and think about what’s different between server and client. Nine times out of ten, it’s something in localStorage or a browser API.</p><p>And when you find it, just use useSyncExternalStore. Tell React what the server value is, what the client value is, and let React do its thing.</p><p>It took me three hours to figure this out. Hopefully, I just saved you two hours and fifty-five minutes. Here’s a link to the full code on <a href="https://github.com/am-miracle/e-commerce-catalog">GitHub</a></p><p>Now go fix that hydration error.</p><p><em>P.S. — If you’re using Zustand with </em><em>persist, literally just copy the cart example from this article. It’ll work. Trust me.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d7a40f2623" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salt-based contract deployment in Solidity: The simple guide]]></title>
            <link>https://medium.com/@judemiracle/salt-based-contract-deployment-the-simple-guide-c4174e115c86?source=rss-648cb35fa9b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4174e115c86</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Jude Miracle]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 13:03:07 GMT</pubDate>
            <atom:updated>2025-07-22T08:05:11.846Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever written tests for Solidity smart contracts, you’ve probably encountered the frustrating “CreateCollision” error. This happens when your tests try to deploy contracts at addresses that are already occupied. It’s a common problem that can make testing feel like a game of whack-a-mole.</p><p>In this guide, we’ll explore salt-based deployment, a simple but powerful technique that solves this problem by giving each contract deployment a unique address. We’ll use real examples from our Vertix NFT marketplace project to show you exactly how it works and when to use it.</p><h4>The Problem</h4><p>When you deploy a smart contract, Ethereum assigns it an address based on the deployer’s address and their current nonce (transaction count). In a testing environment, this creates a predictable pattern that can lead to conflicts.</p><p>Here’s what happens:</p><pre>// Test 1: Deploys contract at address 0x123…<br>new MyContract();<br><br>// Test 2: Tries to deploy at the same address 0x123…<br>new MyContract(); // ❌ CreateCollision error!</pre><p>The problem is that both tests are running in the same environment with the same deployer address and nonce sequence, so they try to use the same addresses.</p><h3>What “CreateCollision” Errors Mean</h3><p>A CreateCollision error occurs when the Ethereum Virtual Machine (EVM) tries to create a contract at an address that already contains code. This is Ethereum’s way of preventing you from accidentally overwriting existing contracts.</p><p>In testing scenarios, this usually means:</p><ul><li>Multiple tests are trying to deploy the same contract type</li><li>The test environment isn’t properly isolated between test runs</li><li>You’re deploying multiple instances of a contract in the same test</li></ul><h4>Real Example from Our Vertix Project</h4><p>In our Vertix NFT marketplace, we encountered this exact problem when testing contract upgrades:</p><pre>function test_Upgrade() public {<br>  // This was failing with CreateCollision<br>  VertixNFTV2Mock newImplementation = new VertixNFTV2Mock();<br><br>  // Upgrade the proxy<br>  nft.upgradeToAndCall(address(newImplementation), &quot;&quot;);<br>}</pre><p>The error trace showed:</p><pre>[1056947008] VertixNFTTest::test_Upgrade()<br>├─ [0] → new &lt;unknown&gt;@0x2e234DAe75C793f67A35089C9d99245E1C58470b<br>└─ ← [Revert] EvmError: Revert</pre><p>The address 0x2e234DAe75C793f67A35089C9d99245E1C58470b was already occupied, causing the deployment to fail.</p><h3>What is Salt-Based Deployment?</h3><p><em>Simple definition: A way to give each contract a unique Address</em></p><p>Salt-based deployment is a technique that uses a unique identifier (called a “salt”) to generate different addresses for the same contract bytecode. Think of it like adding a unique seasoning to each deployment; even though the base contract is the same, the salt makes each instance unique.</p><h3>How it works in plain English</h3><p>Instead of relying on the deployer’s nonce for address generation, salt-based deployment uses a custom value that you provide. This means:</p><ol><li>Same contract + different salt = different address</li><li>Same salt + same contract = same address (deterministic)</li><li>No more address conflicts in your tests</li></ol><h4>The {salt: bytes32(uint256(1))} Syntax</h4><p>The syntax is straightforward:</p><pre>// Traditional deployment<br>new MyContract();<br><br>// Salt-based deployment<br>new MyContract{salt: bytes32(uint256(1))}();</pre><p>The salt parameter takes a bytes32 value, which is why we use bytes32(uint256(1)) to convert a simple number into the required format.</p><h3>How to use it</h3><p>Here are the most common patterns:</p><pre>// Single deployment with salt<br>new MyContract{salt: bytes32(uint256(1))}();<br><br>// Multiple deployments with different salts<br>new MyContract{salt: bytes32(uint256(1))}(); // Address A<br>new MyContract{salt: bytes32(uint256(2))}(); // Address B<br>new MyContract{salt: bytes32(uint256(3))}(); // Address C<br><br>// Using meaningful salt values<br>new MyContract{salt: keccak256(&quot;implementation_v1&quot;)}();<br>new MyContract{salt: keccak256(&quot;implementation_v2&quot;)}();</pre><h4>Different Salt values for different contracts</h4><p>When deploying multiple contract types, you can use different salt ranges:</p><pre>// NFT contracts: salts 1–100<br>new VertixNFT{salt: bytes32(uint256(1))}();<br>new VertixNFTV2{salt: bytes32(uint256(2))}();<br><br>// Governance contracts: salts 101–200<br>new VertixGovernance{salt: bytes32(uint256(101))}();<br>new VertixGovernanceV2{salt: bytes32(uint256(102))}();<br><br>// Escrow contracts: salts 201–300<br>new VertixEscrow{salt: bytes32(uint256(201))}();</pre><h4>Step-by-step implementation</h4><ol><li>Identify the failing deployment</li><li>Add a unique salt value</li><li>Test the fix</li><li>Document your salt choices</li></ol><p>Example implementation:</p><pre>function test_Upgrade() public {<br>  // Step 1: Add salt to prevent collision<br>  VertixNFTV2Mock newImplementation = new VertixNFTV2Mock{salt: bytes32(uint256(1))}();<br>  <br>  // Step 2: Use the new implementation<br>  nft.upgradeToAndCall(address(newImplementation), &quot;&quot;);<br>  <br>  // Step 3: Verify it works<br>  VertixNFTV2Mock upgradedNft = VertixNFTV2Mock(address(nft));<br>  assertEq(upgradedNft.owner(), owner);<br>}</pre><h3>Real example: Fixing our tests</h3><h4>Before: tests failing with CreateCollision</h4><p>Our original test was failing because multiple tests were trying to deploy VertixNFTV2Mock at the same address:</p><pre>function test_Upgrade() public {<br>  // Create collection to test state preservation<br>  vm.prank(creator);<br>  nft.createCollection(NAME, SYMBOL, IMAGE, MAX_SUPPLY);<br>  <br>  // Deploy mock upgraded implementation<br>  vm.startPrank(owner);<br>  VertixNFTV2Mock newImplementation = new VertixNFTV2Mock(); // ❌ Collision here<br>  <br>  // Upgrade the proxy<br>  nft.upgradeToAndCall(address(newImplementation), &quot;&quot;);<br>  vm.stopPrank();<br><br>}</pre><p>The error was:</p><pre>[FAIL: EvmError: Revert] test_Upgrade() (gas: 1056947008)<br>└─ ← [Revert] EvmError: Revert</pre><h4>After: tests passing with Salt deployment</h4><p>After adding salt-based deployment, the test passed:</p><pre>function test_Upgrade() public {<br>  // Create collection to test state preservation<br>  vm.prank(creator);<br>  nft.createCollection(NAME, SYMBOL, IMAGE, MAX_SUPPLY);<br>  <br>  // Deploy mock upgraded implementation<br>  vm.startPrank(owner);<br>  VertixNFTV2Mock newImplementation = new VertixNFTV2Mock{salt: bytes32(uint256(1))}(); // ✅ Unique address<br>  <br>  // Upgrade the proxy<br>  nft.upgradeToAndCall(address(newImplementation), &quot;&quot;);<br>  vm.stopPrank();<br><br>}</pre><p>The result:</p><pre>[PASS] test_Upgrade() (gas: 4530773)</pre><p>The only change was adding {salt: bytes32(uint256(1))} to the deployment, but it completely solved the problem.</p><h3>When to Use It</h3><h4>Testing scenarios</h4><p>Salt-based deployment is most useful in these testing situations:</p><ul><li>Unit tests that deploy multiple contract instances</li><li>Integration tests with complex contract interactions</li><li>Upgrade tests that need multiple implementation versions</li><li>Multi-contract deployment scenarios</li></ul><h4>Multiple contract deployments</h4><p>When your test needs to deploy several contracts:</p><pre>function test_ComplexScenario() public {<br><br>// Each gets a unique address<br>ContractA a = new ContractA{salt: bytes32(uint256(1))}();<br>ContractB b = new ContractB{salt: bytes32(uint256(2))}();<br>ContractC c = new ContractC{salt: bytes32(uint256(3))}();<br><br>// Now they can interact without conflicts<br>a.setContractB(address(b));<br>b.setContractC(address(c));<br><br>}</pre><h4>Contract upgrades</h4><p>Perfect for testing upgrade patterns:</p><pre>function test_UpgradePath() public {<br>  // Deploy multiple versions<br>  ImplementationV1 v1 = new ImplementationV1{salt: bytes32(uint256(1))}();<br>  ImplementationV2 v2 = new ImplementationV2{salt: bytes32(uint256(2))}();<br>  ImplementationV3 v3 = new ImplementationV3{salt: bytes32(uint256(3))}();<br>  <br>  // Test upgrade sequence<br>  proxy.upgradeTo(address(v1));<br>  proxy.upgradeTo(address(v2));<br>  proxy.upgradeTo(address(v3));<br><br>}</pre><h4>Development environments</h4><p>Also useful in development when you need to deploy the same contract multiple times:</p><pre>// Deploy test instances<br>MyContract test1 = new MyContract{salt: keccak256(&quot;test_instance_1&quot;)}();<br>MyContract test2 = new MyContract{salt: keccak256(&quot;test_instance_2&quot;)}();<br>MyContract test3 = new MyContract{salt: keccak256(&quot;test_instance_3&quot;)}();</pre><h3>Best practices</h3><h4>Choose unique Salt values</h4><p>Use a systematic approach to avoid salt conflicts:</p><pre>// Good: Systematic numbering<br>new Contract{salt: bytes32(uint256(1))}();<br>new Contract{salt: bytes32(uint256(2))}();<br>new Contract{salt: bytes32(uint256(3))}();<br><br>// Better: Descriptive hashes<br>new Contract{salt: keccak256(&quot;implementation_v1&quot;)}();<br>new Contract{salt: keccak256(&quot;implementation_v2&quot;)}();<br>new Contract{salt: keccak256(&quot;implementation_v3&quot;)}();</pre><h4>Document your Salt choices</h4><p>Keep track of which salts you’re using:</p><pre>// Salt mapping for our project:<br>// 1–100: NFT contracts<br>// 101–200: Governance contracts<br>// 201–300: Escrow contracts<br>// 301–400: Marketplace contracts<br>new VertixNFT{salt: bytes32(uint256(1))}(); // NFT v1<br>new VertixNFT{salt: bytes32(uint256(2))}(); // NFT v2<br>new VertixGovernance{salt: bytes32(uint256(101))}(); // Governance v1</pre><h4>Keep it simple</h4><p>Don’t overcomplicate it. Start with simple numbered salts and only get fancy when needed:</p><pre>// Start simple<br>new MyContract{salt: bytes32(uint256(1))}();<br><br>// Only add complexity when necessary<br>new MyContract{salt: keccak256(abi.encodePacked(&quot;complex&quot;, &quot;salt&quot;, block.timestamp))}();</pre><h3>Conclusion</h3><p>Salt-based deployment is a simple but powerful technique that solves one of the most frustrating problems in smart contract testing. By adding a unique identifier to each contract deployment, you can avoid CreateCollision errors and create more reliable, isolated tests.</p><p>The key takeaways are:</p><ol><li>Use salt-based deployment when you need multiple instances of the same contract</li><li>Choose unique salt values to avoid conflicts</li><li>Document your salt choices for maintainability</li><li>Keep it simple — start with numbered salts and add complexity only when needed</li></ol><p>In our Vertix project, this simple change transformed failing upgrade tests into reliable, passing tests. The same approach can solve similar problems in your smart contract projects.</p><p>The next time you encounter a CreateCollision error, remember: just add a salt, and your deployment problems will disappear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4174e115c86" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>