<?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 Aneesh Hegde on Medium]]></title>
        <description><![CDATA[Stories by Aneesh Hegde on Medium]]></description>
        <link>https://medium.com/@aneeshhegde7110?source=rss-868e09d5a28a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lX_9FWJJJuFvJdmSlvo1Dw.png</url>
            <title>Stories by Aneesh Hegde on Medium</title>
            <link>https://medium.com/@aneeshhegde7110?source=rss-868e09d5a28a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:29:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aneeshhegde7110/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[Building a Safe Playground for Load Testing]]></title>
            <link>https://medium.com/@aneeshhegde7110/building-a-safe-playground-for-load-testing-77736f0f881a?source=rss-868e09d5a28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/77736f0f881a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[loadtest]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Aneesh Hegde]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 08:58:44 GMT</pubDate>
            <atom:updated>2026-10-07T08:58:44.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qap-0o1Ler8VSVLcx9LaYA.png" /></figure><p><em>(How we built a temporary environment for nine services, protected production from accidental traffic, and discovered that a green test does not always mean a healthy system.)</em></p><p>Imagine running nine microservices that work together to power an application. One handles API requests, another processes messages, another communicates with an AI model, and others manage notifications and background jobs.</p><p>Now imagine asking a simple question:</p><p><strong>What happens when hundreds or thousands of users start using the application at the same time?</strong></p><p>That is where load testing comes in.</p><p>But before sending thousands of requests, we need somewhere safe to send them. An environment that looks like production is useful, but accidentally contacting a real customer, sending an actual notification, or creating an unexpected cloud bill is not part of the experiment.</p><p>This was the problem we wanted to solve: build a temporary environment that could handle realistic load without disturbing production or depending on people remembering to be careful.</p><p>The solution turned into much more than a load-testing setup. It became a lesson in infrastructure isolation, monitoring, automation, and the importance of testing our safety mechanisms themselves.</p><h3>1. The problem: we had tests, but nowhere safe to run them</h3><p>We already had a load-testing suite called voldemort, built using <a href="https://locust.io/">Locust</a>.</p><p>Locust simulates users interacting with an application. Instead of manually opening a app and clicking buttons, we can define user behaviour in code and generate requests automatically.</p><p>Our suite had four test scenarios and an existing CI workflow. CI, or continuous integration, automates tasks such as running tests and deploying applications.</p><p>The missing piece was a safe target for those tests.</p><p>Pointing the suite at a real environment was risky. Some scenarios could create real video rooms, allocate game-server pods, call external vendors, or trigger notifications to actual phone numbers. Some of these integrations could also charge us for every request.</p><p>We needed an environment with two fundamental properties:</p><ul><li>It must not reach real production services or customer data.</li><li>A configuration mistake must not silently create real-world side effects or unexpected costs.</li></ul><p>Simply telling developers to use the correct URLs was not enough. We wanted the infrastructure itself to make unsafe behaviour difficult or impossible.</p><p>We called this temporary environment <strong>hiroshima</strong>. Its lifecycle is simple: create it for testing, use it, and remove it afterwards.</p><h3>2. The architecture: realistic where it matters, simulated where it doesn’t</h3><p>The environment contains the same nine application services as the real platform. However, we deliberately chose which dependencies should be real, which should be simulated, and which should be replaced entirely.</p><p>A dependency is something a service needs to perform its work. For example, a messaging service might depend on a database, a queue, and an external notification provider.</p><p>Our approach was:</p><ul><li><strong>Real PostgreSQL:</strong> to understand how our actual database behaves under load.</li><li><strong>Real Redis:</strong> to exercise the cache configuration expected by the application.</li><li><strong>LocalStack:</strong> to emulate selected AWS services, including queues and object storage.</li><li><strong>A stub gateway:</strong> to replace external vendor APIs with controlled responses.</li><li><strong>Kubernetes:</strong> to run the application services in an isolated namespace.</li><li><strong>Grafana and monitoring exporters:</strong> to observe the system while the test runs.</li></ul><p>Why not make everything real? That would increase cost and risk.</p><p>Why not make everything fake? Then we would learn very little about the behaviour of the actual database and cache.</p><p>The important question was not whether a dependency was real or fake. It was <strong>whether its behaviour mattered to the question we were trying to answer</strong>.</p><h3>Architecture diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ao-LelhAabM9DyBZnzHFDA.png" /><figcaption><em>Figure 1. The temporary load-testing environment and its major components.</em></figcaption></figure><p>The environment runs inside a dedicated Kubernetes namespace. Think of a namespace as a logical room inside a larger cluster: it groups the resources associated with our test.</p><p>Inside that namespace, we run the nine services, LocalStack, the stub gateway, and monitoring components. The real PostgreSQL database and Redis cache are provisioned separately in AWS for the test. An S3 bucket stores run logs.</p><p>During a run, the environment requests approximately 7 GiB of memory. Between runs, application pods are scaled to zero. Kubernetes is responsible for running the containers, while Karpenter can provision a suitable cluster node when capacity is needed.</p><p>This avoids keeping the application workloads running when nobody is testing.</p><h3>3. The run, from beginning to end</h3><p>A temporary environment is only useful if its lifecycle is predictable. We divided the process into six stages.</p><h4>Step 1: Provision the safety boundaries</h4><p>An administrator creates the namespace, resource quotas, resource limits, network policies, and node-pool configuration.</p><p>These are the boundaries around the environment. The test workflow should not be able to casually rewrite the rules that are supposed to protect it.</p><h4>Step 2: Create the temporary infrastructure</h4><p>An approved infrastructure change creates the database, cache, and log bucket.</p><p>Infrastructure changes are reviewed through pull requests. This makes resource creation visible instead of hiding it inside a script.</p><h4>Step 3: Bring up the application</h4><p>The workflow deploys LocalStack, the stub gateway, and all nine application services. It then runs database migrations and inserts synthetic test data.</p><h4>Step 4: Run preflight checks</h4><p>Preflight checks run before any load is generated. They verify that the expected environment is being used, the application can respond, configuration is safe, and monitoring is working.</p><p>A test should not begin simply because Kubernetes says the pods are running.</p><h4>Step 5: Generate traffic and observe the results</h4><p>Locust runs as a Kubernetes Job inside the cluster. A Job runs a task to completion rather than operating as a permanently running service.</p><p>We observe the test using Grafana dashboards, application logs, database measurements, and counters from the stub gateway.</p><h4>Step 6: Tear everything down</h4><p>The workloads are scaled down, temporary resources are cleaned up, and a separately approved infrastructure change destroys the AWS resources.</p><p>There is an important distinction here: <strong>scaling workloads to zero does not mean the cloud bill has stopped</strong>.</p><p>A database or cache can continue to incur charges even when the application is no longer running. Cleanup must account for the actual infrastructure, not just the Kubernetes pods.</p><h3>Run lifecycle diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nqr2iPe6TpYYsdwF1ZAXeA.png" /><figcaption><em>Figure 2. From provisioning and preflight to load generation and cleanup.</em></figcaption></figure><p>The workflow intentionally requires approval at important infrastructure boundaries. This improves review ability, but introduces a trade-off: if the final destruction step is forgotten, resources may remain and continue costing money.</p><p>Automation should make cleanup explicit, verifiable, and difficult to overlook.</p><h3>4. Why some services are fake and others are real</h3><p>One of the most important decisions was determining how to handle dependencies.</p><h4>Queues and object storage: emulate them</h4><p>Our application uses SNS and SQS for messaging. We chose LocalStack to emulate these services inside the test environment.</p><p>Reusing development queues might have seemed convenient, but it would have mixed artificial test messages with developers’ real work. A runaway test could fill those queues or interfere with unrelated debugging.</p><p>Separate real queues were another possibility. However, LocalStack offered several advantages:</p><ul><li>Its messages disappear when the temporary environment is removed.</li><li>Queue depth can be observed directly during the test.</li><li>The test pods do not need AWS credentials to access these emulated services.</li><li>Messaging behaviour can be exercised without using shared development queues.</li></ul><p>There is a limitation: LocalStack does not reproduce every timing characteristic of real SQS. We can use it to test application messaging logic, but we should not claim that its queue latency represents real AWS SQS latency.</p><p>That distinction matters. A useful test result must say what it measures, not just present a number.</p><h3>PostgreSQL and Redis: keep them real</h3><p>The database was one of the main reasons for building the environment in the first place.</p><p>An early version ran PostgreSQL inside Kubernetes. It was cheaper, but its storage, memory, and connection behaviour could differ from the production database.</p><p>A database running in a container can tell us that a database becomes overloaded. It may not tell us when our actual database configuration will reach that point.</p><p>We therefore chose a real Amazon RDS PostgreSQL instance using the production engine version, populated with synthetic test data and removed after the run.</p><p>Redis was treated similarly. The production client expects an ElastiCache endpoint configured for cluster mode. A simple standalone Redis instance might accept a configuration that works in testing but fails in production.</p><p>We chose realism where it changes the answer.</p><h3>External vendors: replace them with a stub gateway</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmUTS-Cm_JRZGyTkxmZacg.png" /><figcaption><em>Figure 3. Choosing between real dependencies, emulated services, and stubbed integrations.</em></figcaption></figure><p>A database emulator cannot prevent a service from contacting an SMS provider, push-notification service, or AI model. We needed another layer.</p><p>We built a small Python service called the <strong>stub gateway</strong>.</p><p>A stub is a controlled substitute that returns a predefined response instead of calling the real service. Our gateway intercepts vendor requests, returns responses in the expected format, and can introduce a configurable delay.</p><p>For example, if an AI-model request normally takes around a second, the gateway can wait for a similar duration before returning a test response. This allows us to exercise the application flow without paying for a real model request.</p><p>It also protects against unintended side effects. A service that normally sends notifications should not be able to send a test campaign to real phone numbers.</p><p>The gateway records both matched and unmatched requests.</p><p>An unmatched request means a service tried to contact an endpoint for which we had not configured a stub. That is a warning sign: we may have missed a vendor integration.</p><p>One lesson became especially important: <strong>mock every endpoint and every direction of a vendor integration</strong>.</p><p>A service may send data to a vendor and separately retrieve information from it. Mocking only the outgoing write request does not guarantee that a later read request is safe.</p><h3>5. Four layers of protection</h3><p>Configuration mistakes happen. Safety should not depend on a single script or a developer remembering every rule.</p><p>We designed multiple layers so that one missed check would not automatically expose production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z5PhSACOQi78G_71xUg0eA.png" /><figcaption>Figure 4. Layered protection against unsafe configuration and external connections.</figcaption></figure><h4>Layer 1: Safe configuration</h4><p>The environment uses dedicated load-test configuration files containing placeholders and test-specific service addresses.</p><p>This makes the intended configuration reviewable in version control without committing generated passwords.</p><h4>Layer 2: Correct configuration loading</h4><p>Having a safe configuration file is not enough. The application must actually load it, and its values must override any earlier configuration that points somewhere else.</p><p>A correct-looking file is useless if the running process ignores it.</p><h4>Layer 3: A boot-time guard</h4><p>Before starting, a guard examines configured endpoints and refuses to proceed when an address points to an unapproved destination.</p><p>This includes database hostnames and cache endpoints, not just HTTP URLs.</p><h4>Layer 4: No AWS identity on the test pods</h4><p>The test pods do not have AWS credentials of their own.</p><p>This is especially important because it removes a capability rather than merely validating a setting. Even if a configuration check misses something, the application cannot simply use its own AWS identity to access a real queue.</p><p>The principle is straightforward: <strong>the safest permission is the permission the workload never had</strong>.</p><p>These controls do not eliminate every possible network path by themselves. Network policy enforcement and independent reachability checks are also essential.</p><h3>6. The guard looked safe. Then we tried to break it.</h3><p>The guard was supposed to prevent unsafe endpoint configuration. It initially looked reasonable, but deliberately testing it with unexpected inputs exposed several defects.</p><p>One problem was that it recognised web-style addresses such as https://api.example.com but missed database and cache hostnames that appeared as plain values.</p><p>For example:</p><pre>DB_HOST=example-staging-db.abc123.rds.amazonaws.com<br>REDIS_HOST=example-dev-cache.abc123.cache.amazonaws.com</pre><p>Because these values did not start with an HTTP scheme, the guard skipped them.</p><p>We tested a staging database and a development cache address. The guard passed even though those values should have been rejected.</p><p>Other defects included:</p><ul><li><strong>Substring matching:</strong> an allowed hostname could accidentally accept a longer, unapproved hostname containing the same text.</li><li><strong>Weak hostname parsing:</strong> ports and credentials were not handled correctly.</li><li><strong>Empty allowlists:</strong> missing configuration could cause an unclear failure.</li><li><strong>Command-line parsing issues:</strong> some patterns could be interpreted as options instead of values.</li></ul><p>The fix required checking the actual shape of endpoint values rather than trusting variable names. A vendor hostname could be stored in a variable named MSG91_BASE, for example, rather than one ending in _URL.</p><p>We also needed to validate internal service addresses. An address can be inside the same Kubernetes cluster and still point to an unapproved namespace.</p><p>The broader lesson is that safety checks need adversarial testing.</p><p>Test malicious inputs that should be rejected, valid inputs that should be accepted, and missing or malformed values. If a check cannot determine whether a configuration is safe, it should fail closed instead of continuing.</p><h3>7. Monitoring: a number without an explanation is not enough</h3><p>Imagine a test reports that a request took two seconds.</p><p>Is the application slow? Is the database overloaded? Is the request waiting for an external service? Or did a queue stop processing messages?</p><p>Latency alone cannot answer those questions.</p><p>We used Grafana to bring application and infrastructure measurements together.</p><p>Two useful monitoring approaches complement each other:</p><ul><li><strong>RED:</strong> Rate, Errors, and Duration — how many requests are happening, how many fail, and how long they take.</li><li><strong>USE:</strong> Utilisation, Saturation, and Errors — how busy a resource is, whether work is piling up, and whether the resource is failing.</li></ul><p>Together, these views help connect symptoms with possible causes.</p><p>For example, if request duration rises while database connections approach their configured limit, the dashboard provides a more useful explanation than a latency graph alone.</p><p>We also added dedicated exporters. An exporter collects information from a system and exposes it in a format that monitoring tools can read.</p><p>The measurements included:</p><ul><li>Queue and dead-letter queue depth.</li><li>PostgreSQL connections and connection limits.</li><li>Redis cache evictions.</li><li>LocalStack disk usage.</li></ul><p>The disk measurement was particularly important because a temporary Kubernetes volume can fill up even when CPU and memory appear healthy. If that happens, Kubernetes may evict the LocalStack pod during a test.</p><p>We also added alerting so that a run would not depend on someone continuously watching a dashboard.</p><h3>8. The latency trap: we were measuring our own waiting</h3><p>The stub gateway deliberately adds delays to simulate external vendors. This is useful for testing request flows, but it can distort performance measurements.</p><p>Consider an API route that makes two or three simulated AI calls. If each call introduces an artificial delay, the route might take several seconds even when the application itself does very little work.</p><p>If we mix those routes with ordinary application requests in one headline latency number, the result becomes misleading.</p><p>We adopted a simple rule:</p><p><strong>Do not combine real processing time and deliberately injected waiting into one headline performance metric.</strong></p><p>For example, p95 latency is the time within which 95% of measured requests complete. If the purpose is to understand application and database performance, the headline metric should exclude routes dominated by artificial vendor delays.</p><p>Those routes can still be measured separately, with their simulated delays clearly labelled.</p><h3>9. A green test is not automatically proof</h3><p>In one sample run, a single virtual user sent 143 requests over five minutes, and none of them failed.</p><p>That’s a good sign, but it doesn’t show that every part of the system did its job. A test can pass even when one part quietly reports success on behalf of another.</p><p>So for a chat message, we checked each step using a different source:</p><ul><li>Locust’s results showed that the request was sent.</li><li>A new row in PostgreSQL showed that the message was saved.</li><li>The AI service’s metrics showed that the request reached that service.</li><li>The service’s logs showed that it tried to call a model.</li><li>The stub gateway’s counter showed that the call went to the stub and not the real vendor.</li><li>A new assistant-message row showed that a reply was written.</li><li>The Messages API response showed that the reply could be read back.</li></ul><p>Checking from several separate places is much more convincing than trusting one green report.</p><h3><strong>10. The biggest surprise: the network rules were not being enforced</strong></h3><p>During preflight, we tried to confirm that an external vendor could not be reached from the test environment.</p><p>Instead, a request to an external endpoint succeeded with HTTP 200.</p><p>That should not have happened.</p><p>The Kubernetes NetworkPolicy resources existed, and our checks confirmed their presence. But the cluster’s networking configuration had policy enforcement disabled, with no alternative policy-enforcing component in place.</p><p>In other words, the cluster accepted the policy objects but did not enforce them.</p><p>This was more serious than a load-testing bug. The setting affected the cluster beyond the test namespace.</p><p>The proposed fix was to enable strict policy enforcement using a deny-by-default approach. Because that change can affect existing workloads across the cluster, it requires careful review and validation.</p><p>This discovery reinforces one of the most important lessons from the project:</p><p><strong>A safety rule existing on paper does not prove that it is enforced.</strong></p><p>The only reliable way to validate a security boundary is to test the actual outcome. If a connection should be blocked, attempt it and confirm that it fails for the expected reason.</p><h3>11. What this environment can — and cannot — tell us</h3><p>The temporary environment gives us a controlled way to compare application changes and observe the real database under load.</p><p>It is useful for studying:</p><ul><li>How a service behaves under controlled traffic.</li><li>Which resource becomes saturated first.</li><li>When the real database begins to struggle.</li><li>How application components behave together.</li><li>Whether a change improves or worsens results under the same conditions.</li></ul><p>But it cannot automatically prove that the entire production platform will behave identically.</p><p>We should not claim that emulated queue timing matches real AWS timing, that artificial vendor delays represent actual vendor latency, or that results from one virtual user predict behaviour under thousands of concurrent users.</p><p>We also need to account for the size and shape of test data, network differences, and whether the monitoring pipeline captures the relevant measurements.</p><p>The best use of this environment is controlled comparison. Run the same workload against the same configuration, change one thing, and observe what improves or gets worse.</p><p>As traffic increases, resources compete, queues grow, and waiting time can increase sharply. We should increase load in stages and measure the resulting behaviour rather than multiplying a low-load result and assuming it predicts production.</p><h3>12. What we learned</h3><p>Building this environment took eleven attempts to bring it up and uncovered roughly forty defects. Some were script mistakes, others were configuration mismatches, and some existed between components that looked correct independently.</p><p>The most useful lessons were these:</p><ol><li><strong>Make unsafe actions fail by default.</strong> Do not rely only on documentation or developer discipline.</li><li><strong>Use real dependencies where realism matters.</strong> Keep the database real when database behaviour is what you need to understand.</li><li><strong>Emulate and stub the rest deliberately.</strong> Isolation and controlled behaviour can be more valuable than reproducing every external system.</li><li><strong>Mock every vendor endpoint and direction.</strong> A missed read endpoint can be just as dangerous as a missed write endpoint.</li><li><strong>Treat monitoring as part of the test.</strong> A measurement that never arrives is not a successful monitoring setup.</li><li><strong>Verify results independently.</strong> Combine request results, database records, application metrics, logs, and stub counters.</li><li><strong>Test the safety controls themselves.</strong> A guard that silently skips a dangerous value is worse than one that clearly refuses to run.</li><li><strong>Verify cleanup.</strong> Scaling pods to zero is not the same as destroying cloud resources.</li><li><strong>Document limitations.</strong> A trustworthy result is one whose boundaries are clearly understood.</li></ol><h3>Conclusion</h3><p>A load-testing environment should do more than generate traffic. It should provide a safe place to experiment, reliable measurements to understand the results, and clear evidence that the experiment behaved as intended.</p><p>Our temporary environment combines nine application services, real database and cache infrastructure, emulated AWS dependencies, stubbed vendor integrations, layered protections, and monitoring.</p><p>It is not a perfect replica of production — and it should not pretend to be one.</p><p>Its value comes from being explicit about what is real, what is simulated, what is protected, and what the results can actually prove.</p><p>The most important outcome was not simply getting a green load test. It was discovering weaknesses in configuration validation, monitoring, cleanup, and network enforcement before trusting the environment with larger experiments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77736f0f881a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking Envoy with WASM: Building a Distributed Breakpoint system]]></title>
            <link>https://medium.com/@aneeshhegde7110/hacking-envoy-with-wasm-building-a-distributed-breakpoint-system-4575db341049?source=rss-868e09d5a28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4575db341049</guid>
            <dc:creator><![CDATA[Aneesh Hegde]]></dc:creator>
            <pubDate>Sat, 16 May 2026 07:31:32 GMT</pubDate>
            <atom:updated>2026-05-16T07:34:21.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H34xZlap8Ly0QsZ-5z4a9w.png" /></figure><h3>TLDR;</h3><p>Debugging a monolith is easy: you set a breakpoint, the execution stops, and you inspect the state. Debugging a microservice mesh is little tricky as the data changes across system very quickly. Modern observability tools (logs, metrics, traces) are great at telling you <em>what</em> broke and <em>when</em>, but they are terrible at telling you <em>why</em>.<br><a href="https://github.com/Aneesh-Hegde/tracery"><strong>Tracery</strong></a> is a distributed debugging tool built to solve this. It brings the monolithic “pause button” to your service mesh.</p><ul><li><strong>The Concept:</strong> Set a distributed breakpoint (e.g., amount &gt; 1000). When triggered, Tracery physically pauses network traffic across your infrastructure, capturing a <strong>Consistent Snapshot</strong> of the network, application memory, and database state at that exact logical millisecond.</li><li><strong>The Architecture:</strong> A central Go Control Plane manages the state machine, while WebAssembly (<a href="https://webassembly.org/">WASM</a>) interceptors inside your <a href="https://www.envoyproxy.io/docs/envoy/latest/intro/what_is_envoy">Envoy</a> sidecars hold the actual network requests open using an asynchronous polling loop.</li><li><strong>In-Flight Mutation:</strong> While a request is paused, you can use the Tracery CLI to rewrite the JSON payload mid-flight and release it, allowing you to test a fix on a live system without redeploying a single line of code.</li></ul><p>Now lets dive deep into what tracery is about.</p><h3>What and why?</h3><p>Lets start imagining with a scenario. Lets suppose you are building a monolith application. How would you debug a problem. Normally what we do is add breakpoints in the execution flow and based on that we are able to detect what the problem is. But what about microservice architecture.<br>Basically what happens in this scenario of microservice architecture is you start with your observatory tools that provide you logs metrics and traces. But the hard truth is logs and traces are fantastic at telling you what happened and when, but they rarely tell you why. By the time you receive an alert and pull up the dashboard, the network connection is closed, the variables are garbage-collected, and the database has been updated by other concurrent requests. There are tools like Sentry that will be helpful but why not give a shot to build it by my own, so here it is.Here how the architecture was build.</p><h3>Architecture</h3><ol><li><strong>The Control Plane: </strong>The Control Plane is a central Go-based server that acts as the source of truth. It exposes a <a href="https://grpc.io/"><strong>gRPC</strong></a><strong> API</strong> for high-speed communication with the CLI and a <strong>Universal HTTP API</strong> for the WASM filters and SDKs.<br><strong>2. Envoy WASM Filter: </strong>It’s a WebAssembly module injected into the Envoy sidecars of your microservices via Istio. Because it runs inside the proxy, it can intercept every request before it even touches your application code.<br><strong>3. Tracery SDK (The Internal Agent):</strong>While the WASM filter sees the network, the SDK will help us to have clear idea of the memory. You import this into your Go services to capture deep internal state stack traces, local variables, and database records. It talks back to the Control Plane to correlate<br><strong>4. Tracery CLI</strong>: A CLI interface to interact with what need to be done.</li></ol><p>Now since we have a high level idea on how this will work lets dive into the detailed implementation for each of this component</p><h3><strong>Detailed workflow on how all these pieces work</strong></h3><h4>1. Control Plane</h4><p>The Control Plane is a Go-based server that acts as the absolute source of truth for the system. It exposes a gRPC API for the CLI and an HTTP API for the WASM filters and SDKs. Its job is straightforward: ingest traces, evaluate them against breakpoint rules, manage the freeze state, and push configurations to the service mesh.<br>Here is exactly how those pieces are implemented.</p><p><em>1. Ingesting Traces via OpenTelemetry</em></p><p>Instead of building a proprietary tracing protocol, Tracery integrates directly with the standard OpenTelemetry (OTel) ecosystem. The Control Plane runs an embedded OTel webhook receiver. The OTelCollector processes incoming protobufs from the mesh, extracts the traceID, service name, endpoint, and attributes, and passes them downstream.</p><p><a href="https://github.com/Aneesh-Hegde/tracery/blob/phase-5/control-plane/otel_collector.go">otel_collector.go</a></p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;go.opentelemetry.io/collector/pdata/ptrace&quot;<br> collectorpb &quot;go.opentelemetry.io/proto/otlp/collector/trace/v1&quot;<br>)<br><br>type OTelCollector struct {<br> collectorpb.UnimplementedTraceServiceServer<br> traceMonitor *TraceMonitor<br>}<br><br>// Export acts as the gRPC webhook receiver for OpenTelemetry traces.<br>// It receives raw trace data from the mesh, converts it, and passes it for processing.<br>func (oc *OTelCollector) Export(ctx context.Context, req *collectorpb.ExportTraceServiceRequest) (*collectorpb.ExportTraceServiceResponse, error) {<br> // 1. Convert incoming protobuf request to internal ptrace structures<br> td := convertToPdata(req) // Abstracted boilerplate<br><br> // 2. Process the parsed traces<br> oc.ProcessTraceData(td)<br><br> return &amp;collectorpb.ExportTraceServiceResponse{}, nil<br>}<br><br>// ProcessTraceData iterates through the telemetry payload, extracts relevant<br>// metadata, and forwards it to the TraceMonitor to check for breakpoints.<br>func (oc *OTelCollector) ProcessTraceData(td ptrace.Traces) {<br> // Abstracted nested loops: Iterate over ResourceSpans -&gt; ScopeSpans -&gt; Spans<br> /*<br>  for each span in td {<br>   // Extract critical routing and identification data<br>   serviceName := extractServiceName(resource)<br>   traceID := span.TraceID().String()<br>   endpoint := span.Name()<br>   attributes := extractAttributes(span.Attributes())<br><br>   // Hand off the extracted data to the TraceMonitor <br>   // to evaluate against active breakpoint rules<br>   oc.traceMonitor.ProcessTrace(traceID, serviceName, endpoint, attributes)<br>  }<br> */<br>}</pre><p><em>2. Detection and Dynamic Rule Evaluation</em></p><p>Once the data is extracted, the TraceMonitor evaluates it against registered breakpoints.</p><p><a href="https://github.com/Aneesh-Hegde/tracery/blob/phase-5/control-plane/trace_monitor.go">trace_monitor.go</a></p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;time&quot;<br><br> // pb &quot;github.com/Aneesh-Hegde/tracery/controlplane/proto/controlplane&quot;<br> pb &quot;github.com/Aneesh-Hegde/tracery/controlplane/proto&quot;<br>)<br><br>type TraceMonitor struct {<br> controlplane *ControlPlaneServer<br>}<br><br>func NewTraceMonitor(cp *ControlPlaneServer) *TraceMonitor {<br> return &amp;TraceMonitor{<br>  controlplane: cp,<br> }<br>}<br><br>func (tm *TraceMonitor) Start() {<br> log.Println(&quot;[TraceMonitor] Starting trace monitoring with breakpoint detection...&quot;)<br><br> //Connect to OpenTelemetry Collector to receive traces<br><br> ticker := time.NewTicker(5 * time.Second)<br> defer ticker.Stop()<br><br> for range ticker.C {<br>  log.Println(&quot;[TraceMonitor] Monitoring active traces...&quot;)<br> }<br>}<br><br>func (tm *TraceMonitor) ProcessTrace(traceID, serviceName, endpoint string, attributes map[string]string) {<br> log.Printf(&quot;[TraceMonitor] Processing trace %s from %s%s&quot;, traceID, serviceName, endpoint)<br><br> breakpoint := tm.controlplane.CheckBreakpoint(serviceName, endpoint, attributes)<br><br> if breakpoint != nil {<br>  log.Printf(&quot;[TraceMonitor] 🎯 Trace %s hit breakpoint %s!&quot;, traceID, breakpoint.ID)<br><br>  event := &amp;pb.TraceEvent{<br>   TraceId:     traceID,<br>   ServiceName: serviceName,<br>   Endpoint:    endpoint,<br>   Timestamp:   time.Now().Unix(),<br>   Attributes:  attributes,<br>  }<br>  tm.controlplane.BroadcastTraceEvent(event)<br><br>  //Trigger freeze<br>  tm.controlplane.OnBreakpointHit(traceID, breakpoint)<br><br> }<br>}<br><br>// SimulateTraceEvent simulates a trace event for string<br>func (tm *TraceMonitor) SimulateTraceEvent(traceID, serviceName, endpoint string, attributes map[string]string) {<br> tm.ProcessTrace(traceID, serviceName, endpoint, attributes)<br>}</pre><p><em>3. Concurrency and State Management</em></p><p>In a microservice environment, a single request (sharing one traceID) might fan out to multiple services concurrently. When a breakpoint is hit, the Control Plane receives simultaneous alerts from multiple Envoy proxies.</p><p>To handle this safely, the FreezeCoordinator acts as the state machine. It uses sync.RWMutex locking to ensure thread-safe transitions between states (e.g., from running to frozen to released). It also manages releaseOverrides, allowing developers to mutate a payload right before un-pausing the request.</p><p><a href="https://github.com/Aneesh-Hegde/tracery/blob/phase-5/control-plane/freeze_coordinator.go">freeze_coordinator.go</a></p><pre>package main<br><br>import (<br> &quot;sync&quot;<br> &quot;log&quot;<br>)<br><br>// FreezeCoordinator acts as the thread-safe state machine for the distributed debugger.<br>// It manages which traces are currently paused across the mesh.<br>type FreezeCoordinator struct {<br> mu               sync.RWMutex<br> frozenTraces     map[string]bool<br> releaseOverrides map[string]string // Stores JSON payloads for in-flight mutation<br> controlplane     *ControlPlaneServer<br>}<br><br>// IsTraceFrozen provides a fast, read-locked check. This is called constantly <br>// by the Envoy proxies to determine if they need to pause an incoming request.<br>func (fc *FreezeCoordinator) IsTraceFrozen(traceID string) bool {<br> fc.mu.RLock()<br> defer fc.mu.RUnlock()<br> return fc.frozenTraces[traceID]<br>}<br><br>// InitiateFreeze officially locks a trace in the frozen state. It uses a write <br>// lock to prevent race conditions and broadcasts the freeze command to the mesh.<br>func (fc *FreezeCoordinator) InitiateFreeze(traceID string, services []string, breakpointID string) error {<br> fc.mu.Lock()<br> defer fc.mu.Unlock()<br> fc.frozenTraces[traceID] = true<br> log.Printf(&quot;[FreezeCoordinator] ❄️ TRAP SET for Trace ID: %s&quot;, traceID)<br> fc.controlplane.BroadcastFreezeEvent(traceID, &quot;frozen&quot;)<br> return nil<br>}<br><br>// ReleaseFreeze drops the lock, allowing the network to resume. If the developer<br>// provided a new JSON body via the CLI, it stages that &#39;override&#39; to be picked up by WASM.<br>func (fc *FreezeCoordinator) ReleaseFreeze(traceID string, override string) error {<br> fc.mu.Lock()<br> defer fc.mu.Unlock()<br> if _, exists := fc.frozenTraces[traceID]; exists {<br>  delete(fc.frozenTraces, traceID) // Clear the lock<br>  if override != &quot;&quot; {<br>   fc.releaseOverrides[traceID] = override // Stage the payload mutation<br>  }<br>  log.Printf(&quot;[FreezeCoordinator] 🟢 RELEASED Trace ID: %s&quot;, traceID)<br>  fc.controlplane.BroadcastFreezeEvent(traceID, &quot;released&quot;)<br> }<br> return nil<br>}<br><br>// PopOverride is called by the proxy to retrieve and atomically clear the staged <br>// payload mutation exactly once when a trace is un-frozen.<br>func (fc *FreezeCoordinator) PopOverride(traceID string) string {<br> fc.mu.Lock()<br> defer fc.mu.Unlock()<br> val := fc.releaseOverrides[traceID]<br> if val != &quot;&quot; {<br>  delete(fc.releaseOverrides, traceID)<br> }<br> return val<br>}<br><br>/* <br>  Abstracted helper functions:<br>  - ListActiveFreezes(): Returns a list of all currently frozen traces (RLock).<br>  - GetFreezeStatus(id): Returns the current state of a specific trace (RLock).<br>*/</pre><h4>2. The WASM Interceptor</h4><p>In an Istio mesh, Envoy proxies act as the way to interact with all traffic. Traditionally, extending Envoy meant writing risky C++ code, if the code crashed, the whole proxy crashed.</p><p><strong>WebAssembly (WASM)</strong> solves this. WASM is a portable, high-performance binary format that runs inside a secure, isolated sandbox. It allows us to safely execute custom logic inside Envoy, if the WASM module panics, Envoy simply catches the error and keeps routing traffic.</p><p>To build the interceptor without writing C++, I used the <strong>proxy-wasm-go-sdk</strong>. However, standard Go compilers produce binaries that are too heavy for WASM environments. To solve this, we used <strong>TinyGo, </strong>a Go compiler specifically optimized for small places like microcontrollers and WebAssembly.</p><p>When I started building Tracery, the proxy-wasm-go-sdk had recently been moved under the official proxy-wasm organization. Because of this transition, much of the official documentation and community tutorials were completely out of date. <br>Using TinyGo&#39;s modern wasip1 target, compiling the filter is straightforward based on the updated documentation:</p><pre>GOOS=wasip1 GOARCH=wasm tinygo build -o main.wasm main.go</pre><p>But at the time, following standard compilation targets often caused the Envoy proxy to crash because it didn’t play nicely with Go’s internal goroutine scheduler. To get a stable, lightweight binary that Envoy would actually accept, I had to explicitly strip out the scheduler and debug symbols. This was the exact command that finally worked for me:</p><pre>tinygo build -o main.wasm -scheduler=none -target=wasi -no-debug main.go</pre><p>But there is a problem.</p><p><strong>The Event Loop Challenge</strong></p><p>With the binary loaded into Istio, the real challenge was the logic. Envoy uses a strict, single-threaded event loop. So we cannot use blocking operations like time.Sleep() to pause a request, or you will freeze the entire proxy and crash the node.</p><p>To build Tracery’s “pause” functionality I had to figure out how to asynchronously hold a specific network request open indefinitely without blocking Envoy’s main worker thread. Here is how the WASM filter achieves that freeze, step by step.</p><p><em>1. The Interception &amp; Body Buffering</em></p><p>The lifecycle starts the moment Envoy parses the HTTP headers. In onHttpRequestHeader, we extract the traceparent ID.</p><p>Crucially, we also strip the content-length header. If a user/developer later decides to mutate the JSON payload before releasing the request, the payload size will change. Removing this header early forces Envoy to recalculate it later, preventing truncated payloads.</p><pre>func (ctx *httpContext) OnHttpRequestHeaders(numHeaders int, endOfStream bool) types.Action {<br> ctx.traceID = ctx.extractTraceID()<br> if ctx.traceID == &quot;&quot; {<br>  return types.ActionContinue<br> }<br><br> // Strip content-length to allow request body mutation later<br> proxywasm.RemoveHttpRequestHeader(&quot;content-length&quot;)<br> <br> ctx.method, _ = proxywasm.GetHttpRequestHeader(&quot;:method&quot;)<br> ctx.path, _ = proxywasm.GetHttpRequestHeader(&quot;:path&quot;)<br> ctx.authority, _ = proxywasm.GetHttpRequestHeader(&quot;:authority&quot;)<br><br> // If no body (GET request), check with the Control Plane immediately<br> if endOfStream {<br>  if ctx.callControlPlane() {<br>   return types.ActionPause<br>  }<br> }<br> return types.ActionContinue<br>}</pre><p>If the request has a payload (like a POST), we need the entire body to evaluate our breakpoint rules. We use onHttpRequestHeader and return types.ActionPause to force Envoy to buffer the stream until endOfStream is true.</p><pre>func (ctx *httpContext) OnHttpRequestBody(bodySize int, endOfStream bool) types.Action {<br> if ctx.traceID == &quot;&quot; { return types.ActionContinue }<br><br> // Force buffering until full body is received<br> if !endOfStream {<br>  return types.ActionPause<br> }<br><br> // Trigger freeze check with the fully buffered body<br> if ctx.callControlPlane() {<br>  return types.ActionPause<br> }<br> return types.ActionContinue<br>}</pre><p><em>2. The Asynchronous Call</em></p><p>As we know we cannot time.Sleep() in a WASM filter as doing so blocks Envoy’s main thread. Instead, we use proxywasm.DispatchHttpCall to asynchronously ask the Control Plane what to do. These is where the magic of WASM comes into play. While this network call is in flight, Envoy safely holds the original request in a paused state thereby providing a asynchronous mechanism and also not effecting the main thread of Envoy.</p><pre>func (ctx *httpContext) callControlPlane() bool {<br> _, err := proxywasm.DispatchHttpCall(<br>  &quot;control_plane&quot;,<br>  [][2]string{<br>   {&quot;:method&quot;, &quot;GET&quot;},<br>   {&quot;:path&quot;, &quot;/check?trace_id=&quot; + ctx.traceID},<br>   {&quot;:authority&quot;, &quot;control-plane&quot;},<br>  },<br>  nil, nil, 5000, ctx.OnCheckResponse,<br> )<br><br> if err != nil {<br>  proxywasm.ResumeHttpRequest() // Fail open if Control Plane is down<br>  return false<br> }<br> return true<br>}</pre><p><em>3. The Freeze Loop and In-Flight Mutation</em></p><p>The most critical part of the filter is the callback function, OnCheckResponse. This is where the actual “freeze loop” lives.</p><p>If the Control Plane replies with &quot;action”: “freeze” , we capture the snapshot, and then we recursively call callControlPlane again. By initiating another asynchronous HTTP call and never calling ResumeHttpRequest, the request remains trapped in Envoy’s memory indefinitely.</p><p>When the Control Plane finally replies with “allow”, we apply any developer-provided body mutations, recalculate the length, and finally release the request to the backend.</p><pre>func (ctx *httpContext) OnCheckResponse(numHeaders int, bodySize int, numTrailers int) {<br> body, err := proxywasm.GetHttpCallResponseBody(0, bodySize)<br> if err != nil {<br>  proxywasm.ResumeHttpRequest()<br>  return<br> }<br><br> action, _ := jsonparser.GetString(body, &quot;action&quot;)<br><br> if action == &quot;freeze&quot; {<br>  proxywasm.LogInfof(&quot;FREEZING Trace: %s&quot;, ctx.traceID)<br><br>  if !ctx.snapshotSent {<br>   ctx.captureAndSendSnapshot()<br>   ctx.snapshotSent = true<br>  }<br><br>  // THE FREEZE LOOP: <br>  // recursively poll the control plane. The request stays paused.<br>  ctx.callControlPlane() <br><br> } else {<br>  proxywasm.LogInfof(&quot;UNFREEZING Trace: %s&quot;, ctx.traceID)<br>  <br>  // If the user modified the body via the CLI, swap it out<br>  overrideBody, err := jsonparser.GetString(body, &quot;override_body&quot;)<br>  if err == nil &amp;&amp; overrideBody != &quot;&quot; {<br>   proxywasm.LogInfof(&quot;✏️ MUTATING BODY: %s&quot;, overrideBody)<br>   currentBody := []byte(overrideBody)<br>   proxywasm.ReplaceHttpRequestBody(currentBody)<br>   <br>   // Recalculate and inject the new content-length<br>   proxywasm.ReplaceHttpRequestHeader(&quot;content-length&quot;, itoa(len(currentBody)))<br>  }<br><br>  // Turn the traffic back on<br>  proxywasm.ResumeHttpRequest()<br> }<br>}</pre><p>This compact WASM module is the backbone of Tracery. It transforms a standard proxy into a highly intelligent interceptor capable of holding traffic indefinitely and rewriting data on the fly.</p><h4>3. The Tracery SDK</h4><p>So far, everything built operates entirely out-of-band at the infrastructure layer. The WASM filter gives us a perfect “Network Snapshot,” but it still leaves one critical question unanswered: <em>Why</em> did the application generate that specific payload?</p><p>To find out, we need to peer past the proxy and inside the application’s memory. This brings us to the future scope of the project i.e the Tracery SDK.</p><p>The SDK isn’t fully built yet, but the architecture is mapped out for upcoming phase. It will be an opt-in Go library that developers import directly into their microservices to capture internal state at the exact millisecond the WASM filter halts the network.</p><p>Here is the blueprint that I have planned:</p><ol><li><strong>Application Snapshots:</strong> Developers will instrument their code with a simple tracery.Checkpoint(). When a distributed freeze is active, the SDK will capture the active goroutine’s stack trace and the local variables tied to that specific traceID. This links the “outside-in” view of the network with the “inside-out” view of the code.</li><li><strong>Smart Database Snapshots:</strong> Traditional debugging often ignores the database. The SDK will introduce RegisterSnapshotQuery. Instead of dumping massive tables, developers can pre-define contextual SQL queries (e.g., select * from orders where id=$1). When a breakpoint hits, the SDK will extract the ID from the frozen request, run the query, and attach just that specific row to the snapshot.</li><li>Building non-blocking application introspection that doesn’t cause issue with the Go garbage collector is a massive runtime challenge, which is why it is slated for Phase 2. But once complete, it will provide the “Consistent Snapshot” of Network, Memory, and Database, all perfectly correlated in time.</li></ol><h4>4. The CLI Interface</h4><p>Infrastructure and SDKs are great, but a tool is only as good as its Developer Experience . For Tracery, that experience lives entirely in the CLI. The CLI acts as the remote control for the Control Plane via gRPC.</p><p>First, you need to know what traffic is flowing. The watch-traces command opens a persistent gRPC stream, giving you a real-time feed of traffic passing through the mesh so you can identify the exact endpoint or service that is misbehaving.</p><p>Once you know where the problem is, you set the trap:</p><pre>tracery set-breakpoint payments-service /charge amount&gt;=1000</pre><p>The moment a request matching that condition hits the Envoy proxy, the network pauses.</p><p>But the real magic happens during the release. Let’s say you inspect the captured snapshot and realize the frontend sent an incorrect JSON payload. In a normal workflow, you’d have to fix the frontend code, recompile, redeploy, and try again.</p><p>With Tracery, you can test the fix <em>in-flight</em>:</p><pre>tracery freeze release — trace &lt;trace-id&gt; — override-body ‘{“amount”: 1000, “currency”: “USD”}’</pre><p>This command sends the new JSON to the WASM filter, swaps out the bad payload for the good one, recalculates the headers, and releases the request to the backend. You just successfully performed surgery on a live microservice transaction without changing a single line of application code.</p><h3>Wrapping Up</h3><p>Tracery was an experiment to see if we could get that pause button back by leveraging Istio, pushing state management to a central Control Plane, and using WebAssembly to hold requests asynchronously.</p><p>While the core logic works, it’s still very much a work in progress. There is plenty of optimization left to do and some early prototyping scripts that need to be cleaned out of the codebase. However, building this project underscored the immense potential of WASM as a tool which I was not aware at all.</p><p>My next focus is building out the Go SDK and polishing the system so it can be easily dropped into any distributed project.</p><p>If you found this concept interesting, you can check out the<strong> </strong><a href="https://github.com/Aneesh-Hegde/tracery"><strong>codebase</strong></a> (note: phase-5 is currently the latest branch with these changes). I am actively looking for feedback, especially from an architectural point of view. If there are any spot areas for improvement, have ideas for new features, or want to help build out the SDK, your critiques and pull requests are highly appreciated!</p><p>My Social: <a href="https://github.com/Aneesh-Hegde">Github</a> <a href="https://www.linkedin.com/in/aneesh-hegde-ba9b68279/">Linkedin</a> <a href="https://x.com/aneesh19_">X</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4575db341049" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>