[{"content":"In engineering, most of our time goes into improving what already exists, one small step at a time. Yet the real gains often lie elsewhere, in optima you cannot see from the bottom of the hole you are digging. And you don&rsquo;t need to be an expert to spot them.\nEverything is an optimization problem Any problem can be seen as a function to optimize, from picking a data structure to setting company strategy. This is not a metaphor: it is a reasoning tool that works at every scale.\nAt Equativ, all our decisions, whether technical, product, sales or marketing, ultimately act on a single quantity: the value created over time.\nThe problem then becomes a space with many dimensions, with a terrain of slopes and valleys.\nFor convenience, we will talk about minimizing a loss rather than maximizing a gain. The best solutions are then the lowest points, and looking for a better solution means digging.\nThe landscape and its local optima An organization improving what it already has is running gradient descent with small steps. It is efficient at reaching the bottom of the valley it is in, and blind to everything beyond its rim.\nThis terrain exists, but it is buried: all you know is the slope under your feet and the spots already probed. Digging means going to see what lies underneath. And in the current valley, you can dig for years without ever going deeper than its floor.\nMost of the work done today consists of going a little deeper into the same local optimum. Each step is rational, but the whole is not necessarily so.\nWeak signals You can tell you are in a local optimum without knowing the domain. The signals are not about technical content, but about the shape of the effort: how the system evolves, who looks after it, how it is explained.\nSignal What it reveals A stack that piles up features, special cases and hacks over the years Small steps keep being added in the same valley instead of rethinking the shape of the problem Nobody feels they own the system Nobody has the mandate, or the wish, to look beyond the rim Old or missing documentation The original mental model is lost, and people optimize without knowing why things are the way they are &ldquo;We&rsquo;ve always done it this way&rdquo; as the only justification The current position is inherited, not chosen A solution picked because it is consensual or trendy The selection criterion is no longer the objective, but comfort or image None of these signals proves that a better optimum exists. Together, they suggest that nobody has looked for one.\nThe method: dig a hole further away When the signals light up, improving what exists is no longer enough. You have to dig elsewhere, starting from scratch, even on a topic you don&rsquo;t master.\nStart from the need, not the solution. Deliberately ignore how it is done today, and ask what should be done. Follow the logic. Common sense and reasoning are the only reliable signal. Habit, authority and fashion are not. Iterate fast and drop without regret. If the hole leads nowhere, dig another one elsewhere. After enough attempts, you almost always find something interesting. Lacking expertise is as much an advantage as a handicap here. Experts know the bottom of their hole perfectly, and that is precisely what keeps them from climbing out.\nThis approach has a name in optimization: random restart, or simulated annealing. When gradient descent stalls, you don&rsquo;t refine the step size, you restart the search from another point. What is obvious for an algorithm is much less so for an organization.\nDig quietly, then communicate Exploring this way often means stepping into other teams&rsquo; scope, and the criticism of not giving notice comes quickly. Staying quiet while digging lightly is a deliberate choice, though: there is nothing to say yet. What triggers communication is not the calendar, it is the signal.\nDig without blast radius. Experiments stay on branches, measurements run on copies of production data, and AB tests cover at most a fraction of a percent of traffic. Nothing is merged into other people&rsquo;s code, nothing is irreversible. A hole that leads nowhere gets filled back in without anyone bearing the consequences.\nWhy not announce every hole. Most holes lead nowhere. Announcing each one draws the owning team&rsquo;s attention and opens a debate on an idea that nothing supports yet. And effort clustering kicks in: faced with consensus, an idea without evidence dies before it has been dug.\nInforming is not asking for permission. The criticism has some truth to it: even a 1% AB test touches production and another team&rsquo;s dashboards. As soon as an experiment leaves the sandbox, a short message to the owners costs little and avoids bad surprises. That message informs, it does not open a debate.\nCommunicate and plan once there is a signal. If the hole turns out to be interesting, you show up with measurements, not a hunch. Only then do you plan larger tests with the teams involved, and possibly a ramp-up. The discussion is now about numbers, and consensus becomes an ally.\nAn example: Motherlode Motherlode is the textbook case. It is an RTB call limiter rewritten from scratch starting in September 2025, by people who were not experts in the field. It sends fewer requests to DSPs for equal or higher revenue, at a much lower inference cost.\nThe starting valley. For each ad request, the RTB engine chooses which DSPs to call: every call costs network and CPU, and only the ones that bid bring revenue. The existing limiter relied on TensorFlow Serving and offline training lagging several hours behind. Its predictions had no physical unit and were compared to thresholds that could be overridden at four levels.\nThe weak signals. Even without machine learning expertise, you could see a critical, niche system, feature-rich to the point of clutter: everything entropy needs to settle in. A quick test confirmed the hunch. Disabling the limiter on a single pod clearly increased revenue in both regions tested. That result does not extrapolate, but a model meant to minimize revenue loss should not be beaten by &ldquo;call everyone&rdquo;.\nStarting from scratch. The reframed objective fits in one sentence: maximize RTB revenue under a call budget. Each partner gets a score with a physical meaning, the expected revenue per call:\n$$ \\text{score} = P(\\text{bid} \\mid \\text{request}) \\times E[\\text{revenue} \\mid \\text{bid}] $$\nThe threshold becomes interpretable too. It follows directly from the network cost of a call and the target margin: below it, calling a DSP costs more than it brings in. The model learns online, in minutes rather than hours.\nSeveral holes before the right one. The path was not linear, and that is the point:\nIn parallel, the rewrite from PyTorch to Rust multiplied performance by 10 to 20, which made each new hole cheaper to dig.\nEvery abandoned lead cost little and taught a lot. A nod to the approach: Motherlode&rsquo;s hyperparameters are tuned by simulated annealing, the philosophy applied to itself.\nThe results. In an AB test on half of a region&rsquo;s traffic, Motherlode matches or beats the existing limiter&rsquo;s revenue while sending significantly fewer requests. In another region, revenue per request sent was noticeably higher. Inference costs a fraction of what it used to, and the expected infrastructure savings are significant.\nThe price of climbing out. In June 2026, the full rollout was nonetheless postponed. Results were uneven across DSPs, the stack was already in the middle of a migration, and investing in two limiters in parallel was deemed inefficient. This is effort clustering at work: the old optimum has its dashboards, its thresholds and its experts, and the new one has to beat it on the old one&rsquo;s metrics.\nWhy we stay stuck If better optima are within reach, why do so few people go looking for them? Three forces keep teams at the bottom of the same hole.\nConsensus and fashion. Teams converge on the solutions everyone talks about. These often address only part of the need, with trade-offs nobody questions anymore. Sometimes they address no need at all and mostly please developers because they look serious. Picking the consensus means picking the hole where everyone is already digging.\nEffort clustering. The more people in a hole, the more it attracts: tooling, hiring, careers and documentation all concentrate there. Every small step is measurable and rewarded. Exploring elsewhere is expensive at first, often fails, and those failures are visible.\nEntropy. A living system accumulates complexity. Every patch raises the walls of the hole, and with them the cost of getting out. Over time, the local optimum becomes a trap, not because it is good, but because leaving it gets more and more expensive.\nThe floor gains a few inches, the walls gain feet. That is why an old system seems indispensable: it is not the best, it has just become very expensive to leave.\nWhat AI changes This approach existed long before AI. AI does not replace it, it changes its cost: digging a hole has become much cheaper.\nMore holes. You can delegate the exploration of several leads in parallel. A prototype that took a week now takes an afternoon, so dropping a lead costs almost nothing.\nHoles further away. AI fills part of the expertise gap and speeds up learning. You can dig far from what you know, in areas you would never have reached on your own. The nature of the problem does not change: AI does not make holes deeper, it widens the area you can explore.\nBut AI also amplifies the opposite tendency. Used to produce the same thing faster, it becomes high-speed gradient descent in the same valley. And since it learned from consensus, it naturally suggests the consensus solution. The gain only exists if you deliberately use it to explore, not to exploit.\nWhat is left to dig Weak signals tell you where to dig, the method tells you how. Two questions remain open, and the second one is probably the most important.\nHow much to explore? The local optimum is not a failure: it is where today&rsquo;s revenue comes from, and most of the work should remain exploitation. Simulated annealing lowers its temperature over time and eventually stops exploring. An organization cannot afford that, because its landscape moves: competitors dig too, and entropy keeps raising the walls. The right share of exploration is never zero, but nobody really knows how to set it.\nHow do you get exploration accepted? Organizations reward small steps, because they are measurable, safe and attributable. A hole that leads nowhere looks like wasted time, even though it has shrunk the area left to explore. And when a hole does lead somewhere, it is asked to beat the old optimum on the old optimum&rsquo;s metrics, as with Motherlode.\nIt is also a matter of culture around risk and the unexpected. A discovery rarely shows up in the planned quarter or within the planned scope, and an organization that plans everything has no room for a result it did not ask for. Demanding zero risk, even for a small and controlled AB test, mostly guarantees staying in the same hole.\nAI shifts this debate. When a hole costs an afternoon instead of a quarter, the risk argument fades, and only culture remains. Do we need an explicit exploration budget? Success criteria designed for the new optimum rather than the old one? A way to count what an empty hole has taught us?\nThe hardest part may not be digging further away. It is accepting that most holes lead nowhere, and counting them as work rather than failures.\nTry it: \/dig-where and \/dig-hole This approach is also packaged as two Claude Code skills, so an agent can apply it with you.\n\/dig-where looks for systems likely stuck in a local optimum, using the weak signals above: accretion, no owner, stale docs, &ldquo;we&rsquo;ve always done it this way&rdquo;, fashion-driven choices. It ranks where a from-scratch rethink could pay off, and never claims more than the signals allow: nobody has probably looked there.\n\/dig-hole digs the hole. It restates the need as a loss with a physical unit, measures both the current system and a trivial baseline, then iterates without blast radius until it reaches a local optimum or abandons the hole for another one. It keeps a dig log along the way, so even an empty hole counts as work.\nRun \/dig-where to pick a spot, then \/dig-hole to dig it.\n","permalink":"https:\/\/ogxd.github.io\/articles\/dig-a-hole-further-away\/","summary":"Most engineering work refines the local optimum we already live in. The real gains often lie elsewhere, and you don&rsquo;t need to be an expert to find them.","title":"Dig a hole further away"},{"content":"What matters most in a company is where the focus is. In engineering, it is very easy to spend hours building solutions to problems that don&rsquo;t exist, and then spend the following years maintaining them, fixing them, and untangling the coupling layers they&rsquo;ve grown with other components.\nEvery company wastes resources this way. But companies without clear objectives, and without the courage to say &ldquo;no&rdquo;, will waste the majority of their resources this way, without ever noticing. Sometimes it ultimately kills the product, and occasionally the company itself.\nSoftware is particularly exposed to this because there is virtually no hardware cost to development: nothing physical stops you from building the wrong thing. And with AI agentic coding, producing code has never been cheaper, so it&rsquo;s never been easier to flood a codebase with solutions nobody asked for. The bottleneck was never writing the code anyway, it&rsquo;s knowing what is worth coding.\nSo how do we know, before building something, how much it will really cost us?\nThe intuition trap Intuitively, we estimate the cost of a solution as proportional to its size: the effort it takes to build, and in software, the amount of code it requires. Big feature, big cost. Small script, small cost. This intuition is wrong, and it&rsquo;s worth understanding why, because it leads to bad decisions on both ends:\nWe greenlight small solutions that end up bleeding us dry for years. We fear large solutions that would actually cost us close to nothing after the initial effort. The size of a solution is the cost of building it. But building is a one-time event, and as we just said, it&rsquo;s cheaper than ever. The real cost is the ownership cost: everything the solution will demand from your team after it&rsquo;s delivered. And that cost is driven by two factors that have little to do with size.\nA meta-heuristic: churn and coupling I propose estimating the ownership cost of a solution with two simple dimensions.\nChurn Churn is how often the solution will change, and by how much. Business rules that evolve every sprint, a UI that follows the product roadmap, an integration with a partner that keeps changing their API: all high churn.\nChurn is expensive because every change is much more than a diff:\nCognitive overhead: someone has to page the solution back into their head, every time. Context switching: back and forth between this solution and whatever the team was actually focused on. Documentation: every change invalidates a bit of the docs, diagrams, and runbooks. Coordination: discussions, reviews, RFCs, release notes, migration announcements&hellip; Coupling Coupling is how tied the solution is to other solutions. It comes in several flavors:\nAPI surface: does it expose an API? How wide is it? How public is it? An internal endpoint used by one consumer is not the same as a public API with external customers building on it. Package dependency: is it a library others depend on? How deep in the dependency tree does it sit? A leaf utility is cheap, while a core package that fifty services transitively pull in is not. Shared state: does it read or write data that other components rely on (a database schema, a message contract, a cache)? Coupling is expensive because it turns your changes into everyone&rsquo;s problem. Every modification must preserve compatibility, or trigger a migration, or break someone. The more coupled a solution is, the more each change costs. And in return, changes in the coupled components will cost you.\nThe formula Here is the heuristic:\n$$ cost \\propto churn \\times coupling $$\nNote that it&rsquo;s a multiplication, not an addition. A solution that changes constantly but that nothing depends on is cheap. A solution that everything depends on but that never changes is cheap too. What is ruinous is the combination of the two: every frequent change rippling through every coupling point.\nAlso note what&rsquo;s absent from the formula: the size of the solution, and its complexity.\nThe four quadrants quadrantChart x-axis Low coupling --> High coupling y-axis Low churn --> High churn quadrant-1 Money pit quadrant-2 Fine quadrant-3 Ideal quadrant-4 Fine Vibe-coded backoffice tool: [0.15, 0.85] Experiment \/ prototype: [0.1, 0.7] Operating system: [0.9, 0.1] Serialization library: [0.75, 0.2] Core API with evolving business rules: [0.85, 0.85] One-shot migration script: [0.1, 0.1] Low churn and low coupling is the ideal, of course. But it&rsquo;s not always achievable: some solutions exist precisely to be depended upon, or precisely to follow a moving business. The good news is that you don&rsquo;t need to be in this quadrant. Either of the two &ldquo;fine&rdquo; quadrants is perfectly sustainable.\nHigh churn, low coupling: fine Take a completely local, vibe-coded backoffice tool. Lots of code, possibly ugly, changing every week as internal users ask for tweaks. By the intuitive &ldquo;cost \u221d code&rdquo; metric, this thing is a disaster. In practice? It costs almost nothing. It&rsquo;s local, nothing depends on it, there is no API contract to honor and no consumers to migrate. If a change breaks it, you fix it or even regenerate it. Churn is high, but it&rsquo;s multiplied by a coupling of nearly zero.\nPrototypes and experiments live here too, as long as they stay decoupled. That&rsquo;s the trap with this quadrant: the cheap experimental tool that quietly gains consumers has just moved to the money pit.\nLow churn, high coupling: fine Now the opposite case: an operating system. It&rsquo;s one of the largest, most complex pieces of software your team uses every day (millions of lines, and more coupling than anything else in your stack, since literally everything runs on top of it). Yet engineering teams don&rsquo;t spend countless hours updating and fixing their OS. They just use it, and it works. Same for the compiler, the standard library, a battle-tested serialization library, or that stable internal package nobody has touched in two years. Massive coupling, near-zero churn, near-zero cost.\nThis is the definitive proof that codebase size and complexity are not the cost. If cost were proportional to code, the OS would dominate every team&rsquo;s maintenance budget. It doesn&rsquo;t even appear on it.\nHigh churn, high coupling: the money pit This is where resources go to die: the solution that changes every sprint and that everything depends on. Every business change forces an API discussion, an RFC, a versioning debate, consumer migrations, and a round of broken builds. Teams in this quadrant feel busy (and they are busy), but most of that effort is friction, not progress.\nThe worst part is that solutions rarely start here. They drift here, one &ldquo;small&rdquo; integration and one &ldquo;quick&rdquo; feature at a time. Which is why the heuristic matters before you build.\nUsing the heuristic Before committing to a solution, ask two questions:\nHow often will this change? Is it tied to a moving business, an evolving product, an unstable partner? Or is the problem well-defined and done once solved? What will depend on it? Who consumes it, through which surface, and how hard would it be to change or kill later? If both answers come back high, that&rsquo;s the moment to push back: narrow the API, make it internal, buy instead of build, or simply say &ldquo;no&rdquo;. Saying no to a high-churn high-coupling solution is one of the highest-leverage engineering decisions a company can make, precisely because the cost it avoids is invisible on any roadmap.\nAnd if you must build it anyway (sometimes the business genuinely demands it), at least attack one of the two factors. You often can&rsquo;t reduce churn since it comes from the outside world. But coupling is a design decision: keep the surface as small and as private as possible, isolate the volatile parts behind stable interfaces, and resist every request to expose &ldquo;just one more endpoint&rdquo;.\nFinally, you can flip the heuristic around for your own comfort: stop feeling guilty about big blobs of decoupled code, and stop fearing large stable dependencies. Ship the 5,000-line internal tool without a design committee. Depend on the huge library that never changes. The code you should lose sleep over is the hundred-line contract that changes every week and that half the company depends on.\n","permalink":"https:\/\/ogxd.github.io\/articles\/coupling-and-churn\/","summary":"What matters most in a company is where the focus is. In engineering, it is very easy to spend hours building solutions to problems that don&rsquo;t exist, and then spend the following years maintaining them, fixing them, and untangling the coupling layers they&rsquo;ve grown with other components.\nEvery company wastes resources this way. But companies without clear objectives, and without the courage to say &ldquo;no&rdquo;, will waste the majority of their resources this way, without ever noticing.","title":"The real cost of engineering: churn and coupling"},{"content":"Dynamic collections, such as the dynamic array (also known as a List in C#), are without a doubt one of the most common data structure, and not only in C# but in computer science in general.\nThe dotnet base class library exposes plenty of dynamic collections to fulfil a wide number of usecases: (System.Collections.)List&lt;T&gt;, Dictionary&lt;K, V&gt;, HashSet&lt;T&gt;, Queue&lt;T&gt;, Stack&lt;T&gt;, and more. But they all share one thing in common: they are based on dynamic reallocation of backing arrays, which can lead to suboptimal performance and excessive memory allocation.\nLet&rsquo;s see how we can optimize this.\nWhat are dynamic collections? A dynamically resizing collection works with one or more backing arrays. Let&rsquo;s take the List&lt;T&gt; as an example. By default, when a List&lt;T&gt; is created, it starts with a backing array of a size of 0 (or simply put no backing array). As the first element is added, a new array is allocated with a size of 4. When the fifth element is added, a new array is allocated with a size of 8, and elements from the old array are copied to the new one. This process is repeated every time the backing array is full, and the process repeats as we keep adding elements.\nHere in this example we can see in red that the operation of adding the fifth element results in the creation of a new array with a larger capacity (8), the copy of the previous elements, the addition of the new element and finally the freeing of the old array (left to the garbage collector when in C#).\nAs you might have guessed, this reallocation follows a $log_{2}$ rule, with the capacity doubling every time the backing array is full. This is a good compromise to minimize the number of reallocations.\nWe can define the number of elements allocated by such model as: $$ g(x)=4(2^{\\operatorname{floor}(\\log_{2}(x))}-1) $$\nLet&rsquo;s say we fill a list with 100 integers. The memory allocated can be calculated as follows:\n$$ g(100)=4\\times(2^{\\operatorname{floor}(\\log_{2}(100))}-1) =4\\times(2^6-1) = 4\\times(64-1) = 4\\times63 = 252 $$\nAs you can see we&rsquo;re allocating 2.5 times more memory than we actually need.\nWe can divide $g(x)$ by $x$ to get the average number of bytes allocated per element. See the result in this Desmos visualization.\nYou can see that we are roughly allocating between 2 and 4 times the memory we actually need, independently of the number of elements.\nA small benchmark Let&rsquo;s benchmark this. Here we&rsquo;ll be using BenchmarkDotNet and .NET 8. The benchmark is ran on an M1 Macbook Pro.\nHere we compare the performance of a List&lt;int&gt; with and without (exact) capacity preallocation.\n[Benchmark] public List&lt;int&gt; Reference() \/\/ WithCapacity() { List&lt;int&gt; listWithoutCapacity = new(); \/\/ new(EntriesCounty); for (int i = 0; i &lt; EntriesCount; i++) { listWithoutCapacity.Add(i); } return listWithoutCapacity; } Here are the results:\nMethod EntriesCount Mean Error StdDev Allocated Reference 50 110.82 ns 1.334 ns 1.248 ns 648 B WithCapacity 50 51.84 ns 1.061 ns 1.179 ns 256 B Reference 5000 5,917.24 ns 61.912 ns 51.699 ns 65840 B WithCapacity 5000 4,060.86 ns 59.039 ns 65.622 ns 20056 B Reference 500000 888,194.09 ns 17,660.545 ns 33,170.784 ns 4195192 B WithCapacity 500000 471,742.47 ns 5,221.942 ns 4,629.116 ns 2000272 B As you can see, the collection with preallocated capacity uses less CPU times and allocates less memory.\nHow to improve the performance? Set capacity to known size in the collection&rsquo;s constructor In dotnet, the optimal solution is to preallocate such collections using the capacity argument available in constructors for most of theses collections. However, it&rsquo;s not always possible to know the exact number of elements that will be added to the collection.\nOther solutions have their own drawbacks, and share in common the fact that it will complexify the code and make it harder to maintain, so at this point we may want to profile prior to embarking on such optimizations.\nSet capacity to maximum known size Sometimes, we may know the maximum size of the collection. In such case, it can be beneficial to preallocate the collection with the maximum size.\nOne example is when we extract or filter elements out of an existing collection:\nList&lt;int&gt; input = ... \/\/ The output may contain *at most* input.Count elements \/\/ Thus we can preallocate the output list with a capacity of input.Count List&lt;int&gt; output = new List&lt;int&gt;(input.Count); foreach (var i in list) if (ShouldKeep(i)) output.Add(i); It&rsquo;s a bit more tricky when using Linq expression as the ToList() method does not take a capacity argument (that&rsquo;s unfortunate!), still, it&rsquo;s possible:\nList&lt;int&gt; input = ... List&lt;int&gt; output = new List&lt;int&gt;(input.Count); output.AddRange(input.Where(ShouldKeep)); This optimization, when doable, has the benefit of not complexifying the code too much, however it may result in oversized backing arrays depending on the context.\nIterate twice An underrated technique is to iterate twice: once to count the number of elements (then we can set the exact capacity), and once to add the elements. This technique is particularly useful when the cost of iterating twice is cheap compared to the cost of reallocation. Plus, the capacity is now set to the exact size of the collection.\nList&lt;int&gt; input = ... \/\/ Iterate once to count the number of elements int count = 0; foreach (var i in input) if (ShouldKeep(i)) count++; \/\/ Preallocate the output list with the exact capacity List&lt;int&gt; output = new List&lt;int&gt;(count); \/\/ Iterate a second time to add the elements foreach (var i in input) if (ShouldKeep(i)) output.Add(i); As you can see, here we are bloating the code a bit. Plus, the performance gain is very context-dependent.\nHardcoded heuristics In some situations, the average size of a collection in a piece of code can be estimated, either from the context or from metrics. Let&rsquo;s say you need to list all metro stations a Parisian would pass by in a day. It would likely be somewhere between 1 and 20, but never 1000. So we could hardcode a capacity of let&rsquo;s say 15 and consider it better than no capacity at all.\nA drawback is that it may bring your coworkers to ask you why you chose 15 and not 20, or 10, or 5. It&rsquo;s also difficult to maintain, as the context may change over time. So you&rsquo;d likely add comments to explain your choice, and start doubting your own choice when you read back your code a few months later&hellip; meh.\nPredictive sizing heuristics Here is the last technique, and the reason as of why I chose to write this article. This technique is about tracking the final sizes of collections to compute a sizing that can then be used to preallocate future instances of same collections.\nRetrieving the final size of a collection The trickiest part is to track final sizes of the collections. In order to know the final size of let&rsquo;s say a List&lt;int&gt;, we need to know when it&rsquo;s done being used. By chance, the garbage collector just does that in it&rsquo;s first phase (a.k.a. the Mark phase) when it finds unreachable objects. We can leverage the finalizer (a.k.a. destructor) of an object to know when it&rsquo;s done being used.\nMost dotnet generic collections aren&rsquo;t sealed, thus we could inherit from them and implement such finalizer. However, this has several drawbacks:\nWe find inheriting from collections to not be very elegent, and possibly confusing for other developers. Plus we&rsquo;d have to repeat this for every collection type we want to track. It would mean that a finalizer would be invoked for every collection that is garbage collected, which is not very efficient. We could use GC.SuppressFinalize to achieve some kind of sampling, only keeping finalizers for a fraction of the collections, but it really feels like duct tape plumbing. What about sealed collections? An interesting alternative is to use an ConditionalWeakTable to associate an object dedicated to tracking the final size of a collection (let&rsquo;s call this class Finalizer) to the collection itself. Here is a comment from the ConditionalWeakTable source code:\n\/\/ Lifetimes of keys and values: \/\/ Inserting a key and value into the dictonary will not \/\/ prevent the key from dying, even if the key is strongly reachable \/\/ from the value. Once the key dies, the dictionary automatically removes \/\/ the key\/value entry. In our context, that means that the value (Finalizer) can reference the key (the collection) without preventing the collection from being garbage collected. This is exactly what we need. When the collection is garbage collected, the Finalizer object will be garbage collected as well, invoking it&rsquo;s finalizer method, which accesses the collection size to update the predictive sizing.\nWe this solution, we can chose to only track a fraction of the collections (reducing the overhead of the finalizers). Plus, this solution is generic and can be applied to any collection type.\npublic class MyListFactory { private readonly ConditionalWeakTable&lt;List&lt;T&gt;, Finalizer&gt; _weakTable; private int _recommendedCapacity; private List&lt;T&gt; CreateList&lt;T&gt;() { List&lt;T&gt; list = new(_recommendedCapacity); if (ShouldTrack(list)) _weakTable.Add(list, new Finalizer(list, this)); return list; } private void Update(int count) { _recommendedCapacity = ... } class Finalizer(List&lt;T&gt; list, MyListFactory&lt;T&gt; factory) { ~Finalizer() { factory.Update(list.Count); } } } Computing the optimal size From the final sizes, we now need to compute the optimal size. There aren&rsquo;t a single approach to this, but we chose to use the average multiplied by some factor, and clamped to a maximum value. In our implementation we made the factor and maximum configurable, but we chose 1.3 and 65536 as default values (1.3 seemed like a good compromise in our tests, and when the collection stores bytes, 65536 is highest power-of-two that remains below the LOH threshold of 85K bytes).\nAs a this development purpose is only optimization, we&rsquo;d also make this the computation of the heuristic is optimized as well. In this context, we avoid any kind of loop for computing any kind of statistics, and only rely on &ldquo;running&rdquo; methods. A way to compute a running average is to store a limited numbers of sizes in a doubly linked list and store the sum of the sizes. When a new size is added, we remove the oldest size from the sum, add the new size, and update the list. This way we can compute the average in constant time. We then make this &ldquo;window&rdquo; configurable. The wider the window, the more accurate the average, but the more memory it consumes and the slower it is to update if new patterns emerge.\nAnother concern is thread safety: computing averages and other statistics in a thread-safe manner can be very complex, however we&rsquo;re fortunate that the finalizers are invoked in a single thread (called the finalizer thread) -at least that&rsquo;s how it is as of .NET 10-. Thus we&rsquo;ll simple protect ouserlves for a potential future change with a lock, and do our computations without caring much about thread-safety.\nHandling uneven distributions Until now, we&rsquo;ve assumed that the distribution of sizes is roughly even. However, in some cases, the distribution can be very uneven. In such cases, the predictive sizing will have a limited effect. Let&rsquo;s say for instance that the size of a collection is either 0 or 10000: the average will be 5000, and the predictive sizing will be 6500 (assuming a factor of 1.3). This is not enough to prevent reallocation (at 8192 elements the backing array will be reallocated to 16384), and it also wastes memory when the size is 0.\nWhile we are not sure how to keep the optimization effective in this situation, we can at least detect such case to fallback to not using any capacity at all. This way, the optimization can be used without risk of making things worse.\nAn approach to detect uneven distribution is to compute the Margin of Error (MOE) and normalize it to an [0; 1] range so that we can compare it to a configurable threshold. The MOE is computed as the standard deviation divided by the average. A high MOE means that the distribution is uneven. We can then use a threshold to decide if we should use the predictive sizing or not.\nThe MOE is defined by $MOE=\\frac{\\sigma}{\\sqrt{n}}$, where $\\sigma$ is the standard deviation and $n$ is the number of samples. The MOE can be normalized to a [0; 1] range by dividing it by the average. That gives us:\n$$ MOE_{normalized}=\\frac{MOE}{\\mu} =\\frac{\\frac{\\sigma}{\\sqrt{n}}}{\\mu} =\\frac{\\frac{\\sigma}{\\sqrt{n}}}{\\frac{sum}{n}} =\\frac{\\sigma\\sqrt{n}}{sum} $$\nThe closer to 0, the more even the distribution is, and the closer to 1, the more uneven it is. We can then compare this value to a threshold, and, if above, use 0 as the predictive size.\nComputing a running standard deviation Since our distribution estimator is based on the standard deviation, we need to find a way to compute it in a running manner, as we did for the average. Usually, the standard deviation formula is defined as: $\\sigma=\\sqrt{\\frac{\\sum_{i=1}^{n}(x_i-\\mu)^2}{n}}$, where $\\mu$ is the average.\nTranslating this formula to code as-is means we&rsquo;d need to iterate over all sizes to evaluate the sum of the squares of the differences. We need another approach to compute this in a running manner.\nWe can expand the square and split the sums:\n$$ \\sum_{i=1}^{n} (x_i - \\mu)^2 =\\sum_{i=1}^{n} (x_i^2 - 2x_i\\mu + \\mu^2) =\\sum_{i=1}^{n} x_i^2 - 2\\mu\\sum_{i=1}^{n} x_i + n\\mu^2 =\\sum_{i=1}^{n} x_i^2 - 2n\\mu^2 + n\\mu^2 =\\sum_{i=1}^{n} x_i^2 - n\\mu^2 $$\nHere we managed to take $\\mu$ out of a sum, making it possible to compute $\\sigma$ in a running manner. This is done the same way as for the average, with the difference that we store the sum of squared sizes (as opposed to the sum of sizes).\nPutting it all together Here is the code computing the predictive sizing, taking into account all the above considerations:\nprivate readonly int _windowSize; private readonly int _maxCapacity; private readonly double _factor; private readonly double _spreadThreshold; private readonly OptimizedLinkedList&lt;int&gt; _measurements; private int _sum; private int _sumOfSquares; \/\/ Triggered by the finalizer when a collection is garbage collected private void Update(int count) { \/\/ Thanks to the minIntervalMs parameter, we expect this method to not be called too often, \/\/ avoiding contention on the underlying lock. lock (_measurements) { \/\/ Compute sliding sum and sliding sum of squares without iterating thanks to the linked list. \/\/ This then allows efficient computation of mean and variance. _measurements.AddLast(count); _sum += count; _sumOfSquares += count * count; if (_measurements.Count &gt;= _windowSize) { _measurements.RemoveFirst(out int removedValue); _sum -= removedValue; _sumOfSquares -= removedValue * removedValue; } double mean = 1d * _sum \/ _measurements.Count; \/\/ Alternnative formula for computing standard deviation in a running manner double stddev = Math.Sqrt((1d * _sumOfSquares \/ _measurements.Count) - (mean * mean)); \/\/ Use the MOE \/ mean to quantify how uneven the distribution is. double spread = stddev * Math.Sqrt(_measurements.Count) \/ _sum; \/\/ If the spread is too high, we consider the heuristic unreliable and we set the capacity to 0. _recommendedCapacity = spread &gt; _spreadThreshold ? 0 : Math.Min(_maxCapacity, (int)(_factor * mean)); } } You you&rsquo;ll find a fully working implementation in this gist.\nBenchmarks Let&rsquo;s run a new benchmark where we compare how the different techniques perform. Keep in mind techniques are meant to be used in different contexts, and as any benchmarks, the numbers are &ldquo;artificial&rdquo; and may not reflect the performance in your specific context. This serves as a hint on how the techniques compare in a specific context.\nHere we benchmark time but most importantly memory allocation. We filter out 200000 elements out of a list of 550000 and return a list of the remaining 350000 elements. In such context:\nReference is no capacity preallocation (NoPreAllocate) If the output size is known in advance, we may simply set the capacity to the output size (PreAllocateExact) If the input size is known in advance, we may employ the technique of setting the capacity to the exact size (PreAllocateMax) If the filtering is cheap, we may iterate twice and use exact capacity (PreAllocateExactIterTwice) If the distribution is even enough, we may use predictive sizing (WithPredictiveSizing) Method Mean Error StdDev Allocated NoPreAllocate 1.554 ms 0.0429 ms 0.0629 ms 4 MB PreAllocateExact 1.289 ms 0.0423 ms 0.0593 ms 1.34 MB PreAllocateMax 1.244 ms 0.0200 ms 0.0267 ms 2.1 MB PreAllocateExactIterTwice 2.066 ms 0.0396 ms 0.0554 ms 1.34 MB WithPredictiveSizing 1.230 ms 0.0242 ms 0.0323 ms 1.74 MB Todo (WithPredictiveSizing 1.3 ratio alloc)\nSummary Todo\nContext Technique Drawback(s) Example Size is known Set capacity to known size in collection&rsquo;s constructor Maximum size is known Set capacity to maximum known size - Might result in oversized backing arrays depending on the context test Iteration cost is cheap Iterate twice - Adds complexity - Cost of iterating twice Average size at runtime is roughly known (eg from metrics) Hardcoded heuristics - Adds complexity - Difficult to maintain None of the above Predictive sizing - Adds complexity - Limited effect when distribution is very uneven ","permalink":"https:\/\/ogxd.github.io\/articles\/pre-allocated-collections\/","summary":"Dynamic collections, such as the dynamic array (also known as a List in C#), are without a doubt one of the most common data structure, and not only in C# but in computer science in general.\nThe dotnet base class library exposes plenty of dynamic collections to fulfil a wide number of usecases: (System.Collections.)List&lt;T&gt;, Dictionary&lt;K, V&gt;, HashSet&lt;T&gt;, Queue&lt;T&gt;, Stack&lt;T&gt;, and more. But they all share one thing in common: they are based on dynamic reallocation of backing arrays, which can lead to suboptimal performance and excessive memory allocation.","title":"Optimizing C# collections with predictive sizing"},{"content":"The GitLab CI ecosystem is full of features and integrations that make it a powerful tool for building, testing, and deploying your applications. It comes with an integrated package registry to share and manage your packages. However, the GitLab SaaS API (gitlab.com) comes with rate-limits which can be a problem for scaling CI\/CD pipelines, and quite frustrating when you hit them.\nIn this article, I will share a solution I find odd yet very effective: implementing a caching proxy in front of the NuGet GitLab package registry.\nThis article isn&rsquo;t a tutorial, but it will provide all required information and gotchas if you want to set up your own caching proxy over the GitLab package registry to improve your CI\/CD experience.\nThe problem The gitlab.com API rate limits All requests to the gitlab.com are rate-limited. The rate limits are different for authenticated and unauthenticated requests, and depending on the scope.\nIn the context of the package registry, the rate limits are as follows:\nUnauthenticated requests: 500 requests per minute (per IP) Authenticated requests: 2000 requests per minute (per user) This isn&rsquo;t that much, even for a medium-sized team. Backend, frontend, QA, deployments&hellip; all of these will count towards the rate limit until you hit the limit and get in return a 429 HTTP status code, which will cause your job and pipeline to fail, resulting in a bad and frustrating developer experience and a waste of time.\n\/usr\/share\/dotnet\/sdk\/8.0.404\/NuGet.targets(174,5): error : Response status code does not indicate success: 429 (Too Many Requests). How to solve this? As specified in the gitlab.com handbook, no bypass is allowed, so you can&rsquo;t ask for a rate limit increase. How can you scale your CI\/CD pipelines without hitting the rate limits?\nAnd if our package registry is private and the token used is the CI_JOB_TOKEN, the rate-limit that would apply would be 2000 requests per minute per project, no?\nUnfortunately, gitlab.com provides no logs and no metrics, and you&rsquo;ll see that what happens behind the scenes is quite surprising.\nUnauthorized requests to the package registry The first finding we found out thanks to the debug logs the proxy (we&rsquo;ll talk about it later) is that the dotnet NuGet client will always start with an unauthenticated request to the package registry, even if the NuGet source is configured with a token. The first call to the registry is to get subsequent endpoints, which does not require authentication. The second and third calls are to get the metadata (package versions) and download the package, which require authentication.\nThis results in a 401 Unauthorized response from the registry (which includes a www-authenticate header in the response), and the client will then retry with the token.\nsequenceDiagram Runner->>Registry: \/index.json activate Registry Registry-->>Runner: \u2705 List of endpoints deactivate Registry Runner->>Registry: \/metadata\/mypackage\/index.json activate Registry Registry--xRunner: 401 Unauthorized \u274cWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Registry Runner->>Registry: \/metadata\/mypackage\/index.jsonAuthorization: Basic ABCDEFG1234 activate Registry Registry-->>Runner: \u2705 List available versions deactivate Registry Runner->>Registry: \/download\/mypackage\/1.2.3\/mypackage.1.2.3.nupkg activate Registry Registry--xRunner: 401 Unauthorized \u274cWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Registry Runner->>Registry: \/download\/mypackage\/1.2.3\/mypackage.1.2.3.nupkgAuthorization: Basic ABCDEFG1234 activate Registry Registry-->>Runner: \u2705 mypackage.1.2.3.nupkg deactivate Registry This implies two things:\nWe have twice as many requests as we actually need (which counts towards the rate limit) The first request being unauthenticated, it counts against the unauthenticated rate limit (500 requests per minute). This means that even if you have a token, the first call being unauthenticated, you&rsquo;d hit the unauthenticated rate limit before the authenticated one. That&rsquo;s a bummer&hellip; this effectively means all of our projects are limited by the same rate limit, even if they have a different token. Plus the fact that the unauthenticated rate limit is the lowest of all, and that all requests are doubled.\nThat also implies we&rsquo;re rate-limited by IP, which can be a problem if you have a lot of runners behind the same public IP.\nParallel fetching for NuGet sources Another finding is that the dotnet NuGet client will fetch the metadata for all sources in parallel. For instance, if your project depends on a public package like xunit, the client will fetch the metadata for xunit from nuget.org but also from your private GitLab package registry, even if you don&rsquo;t have any xunit package in your registry (it ends up in 404).\nThis results in a lot of unnecessary requests to the Gitlab package registry, and again, counts towards the rate limit. Given how many Microsoft.* and System.* packages we usually have in our projects (to name a few), this can be a lot of requests.\nsequenceDiagram participant Runner participant Registry participant Nuget#46;org Runner->>Nuget#46;org: \/metadata\/xunit\/index.json activate Nuget#46;org Runner->>Registry: \/metadata\/xunit\/index.json activate Registry Registry--xRunner: \u274c 401 UnauthorizedWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Registry Runner->>Registry: \/metadata\/xunit\/index.jsonAuthorization: Basic ABCDEFG1234 activate Registry Registry-->>Runner: \u274c 404 Not Found deactivate Registry Nuget#46;org-->>Runner: \u2705 List of packages deactivate Nuget#46;org Runner->>Nuget#46;org: \/download\/xunit\/2.9.3\/mypackage.2.9.3.nupkg activate Nuget#46;org Runner->>Registry: \/download\/xunit\/2.9.3\/mypackage.2.9.3.nupkg activate Registry Registry--xRunner: \u274c 401 UnauthorizedWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Registry Runner->>Registry: \/download\/mypackage\/2.9.3\/mypackage.2.9.3.nupkgAuthorization: Basic ABCDEFG1234 activate Registry Registry-->>Runner: \u274c 404 Not Found deactivate Registry Nuget#46;org-->>Runner: \u2705 xunit.2.9.3.nupkg deactivate Nuget#46;org This issue can be addressed with the help of the Package Source Mapping feature, but it requires manual work and maintenance in each project. That said, it is considered a good practice for security reasons (prevents supply chain attacks), so it&rsquo;s at least worth a look.\nCaching packages with a read-through caching proxy The most effective solution we found was to implement a proxy in front of the Gitlab package registry, not only to cache packages, but also to handle unauthenticated requests (401) and requests for packages that are not in the registry (404), hence reducing the overall number of requests, but also avoiding the unauthenticated rate limit.\nChoose your weapon There are many HTTP proxies available out there to achieve this. The requirements are for the proxy to be able to cache, preferably in-memory, be able to defines some rules over headers and paths, and be able to edit headers and response bodies. We chose to go with our own implementation using rust and hyper.rs, but proxies like Nginx and HAProxy are also good choices.\nSee the configuration we used for cacheus.\nReplacing the endpoints The initial request to the GitLab package registry will return a list of endpoints. Unfortunately, these endpoints are on the gitlab.com domain, so we need to replace the domain with the domain of our proxy for NuGet to continue fetching through our proxy. The logic is simple: if the path is \/api\/v4\/groups\/xxxxx\/-\/packages\/nuget\/index.json (check what yours is), we replace all occurrences of gitlab.com with our proxy domain in the response body.\nFirst call without authorization header The second rule is to return a 401 to all requests that don&rsquo;t have an Authorization header. This will prevent the client from retrying with the token, and will also prevent the request from counting towards the rate limit. A special header WWW-Authenticate: Basic realm=&quot;GitLab Package Registry&quot; but also be added to the response to make the client understand that it needs to authenticate. This way we are no longer rate-limited by IP, nor to the lowest rate limit, and we divide the number of requests by two.\nsequenceDiagram participant Runner participant Proxy participant Registry Runner->>Proxy: \/metadata\/mypackage\/index.json activate Proxy Note over Proxy: \"Authorization\" header is missing Proxy--xRunner: \u274c 401 UnauthorizedWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Proxy Calls for nuget.org packages on private registry We chose to return a 404 from the proxy itself for most requests for packages that are not in the registry. We achieved this by looking for the presence of metadata\/microsoft., metadata\/system. or metadata\/xunit in the request path. This won&rsquo;t cover all cases, but we found out that it would remove about 70% of the requests made to the registry for our main projects.\nsequenceDiagram participant Runner participant Proxy participant Registry Runner->>Proxy: \/metadata\/xunit\/index.jsonAuthorization: Basic ABCDEFG1234 activate Proxy Note over Proxy: Path contains \"metadata\/xunit\" Proxy--xRunner: \u274c 404 Not Found deactivate Proxy Caching the metadata and packages Finally, we can cache the response of the remaining calls. The metadata shall not be cached for too long since it can change (eg you just released a new package), but the packages can be cached for much longer since they are immutable for a given version. We chose to cache the metadata for 1 minute and the packages for 1 day. This is all done in-memory with a simple LRU cache. Some developers were concerned by the potential memory usage of the cache, but we found out it wouldn&rsquo;t get above 300mb for 500 packages, which is very reasonable.\nHttps \/ .NET 9 One last but important detail: dotnet 9 made it mandatory to use HTTPS for a package sources. It can be disabled with --allow-insecure-connections when adding the NuGet source, but otherwise it&rsquo;s best to have a valid certificate on your proxy (or on your ingress if you use one).\nResults Here is what our I\/O looks like using the proxy, considering the cache is empty (which is the worst case scenario, and quite unlikely once the cache has already been solicited for a few jobs).\nsequenceDiagram participant Runner participant Proxy participant Registry Runner->>Proxy: \/metadata\/mypackage\/index.json activate Proxy Proxy--xRunner: \u274c 401 UnauthorizedWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Proxy Runner->>Proxy: \/metadata\/mypackage\/index.jsonAuthorization: Basic ABCDEFG1234 activate Proxy Proxy->>Registry: \/metadata\/mypackage\/index.jsonAuthorization: Basic ABCDEFG1234 activate Registry Registry->>Proxy: \u2705 List of packages deactivate Registry Note over Proxy: Cache for 1 minute Proxy->>Runner: \u2705 List of packages deactivate Proxy Runner->>Proxy: \/download\/mypackage\/1.2.3\/mypackage.1.2.3.nupkg activate Proxy Proxy--xRunner: \u274c 401 UnauthorizedWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Proxy Runner->>Proxy: \/download\/mypackage\/1.2.3\/mypackage.1.2.3.nupkgAuthorization: Basic ABCDEFG1234 activate Proxy Proxy->>Registry: \/download\/mypackage\/1.2.3\/mypackage.1.2.3.nupkgAuthorization: Basic ABCDEFG1234 activate Registry Registry->>Proxy: \u2705 mypackage.1.2.3.nupkg deactivate Registry Note over Proxy: Cache for 1 day Proxy->>Runner: \u2705 mypackage.1.2.3.nupkg deactivate Proxy Here is what it looks like in the best case scenario:\nsequenceDiagram participant Runner participant Proxy participant Registry Runner->>Proxy: \/metadata\/mypackage\/index.json activate Proxy Proxy--xRunner: \u274c 401 UnauthorizedWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Proxy Runner->>Proxy: \/metadata\/mypackage\/index.jsonAuthorization: Basic ABCDEFG1234 activate Proxy Note over Proxy: Cache hit! Proxy->>Runner: \u2705 List of packages deactivate Proxy Runner->>Proxy: \/download\/mypackage\/1.2.3\/mypackage.1.2.3.nupkg activate Proxy Proxy--xRunner: \u274c 401 UnauthorizedWWW-Authenticate: Basic realm=\"GitLab Package Registry\" deactivate Proxy Runner->>Proxy: \/download\/mypackage\/1.2.3\/mypackage.1.2.3.nupkgAuthorization: Basic ABCDEFG1234 activate Proxy Note over Proxy: Cache hit! Proxy->>Runner: \u2705 mypackage.1.2.3.nupkg deactivate Proxy As you can see, the proxy and cache are able to handle a large portion of the requests without calling the Gitlab package registry. In practice, we observe a reduction of I\/Os between 80% and 100%. This combined with the fact that we&rsquo;re now theoretically rate-limited to 2000 requests per minute per project instead of 500 globally, we can now scale our CI\/CD pipelines without fearing of hitting the rate limits again \ud83c\udf89.\n","permalink":"https:\/\/ogxd.github.io\/articles\/nuget-caching\/","summary":"The GitLab CI ecosystem is full of features and integrations that make it a powerful tool for building, testing, and deploying your applications. It comes with an integrated package registry to share and manage your packages. However, the GitLab SaaS API (gitlab.com) comes with rate-limits which can be a problem for scaling CI\/CD pipelines, and quite frustrating when you hit them.\nIn this article, I will share a solution I find odd yet very effective: implementing a caching proxy in front of the NuGet GitLab package registry.","title":"A solution to gitlab package registry 429's errors"},{"content":"In this article I&rsquo;d like to share my journey learning about caching, and my research on how to make it more efficient. This article is the first in a serie of articles about caching, and here we&rsquo;ll start by discussing the challenges and memory considerations when doing in-memory caching.\nThis was done as part of my day job as a Staff backend engineer at Equativ, a leading provider of digital advertising solutions, offering a range of products and services to help businesses reach their target audiences and achieve their marketing goals.\nAt Equativ, we solve scalability issues with distributed service-oriented architecture, but that comes at the cost of increased network I\/Os which can impact performance and latency negatively. In this context, caching is critical.\nCaching helps reduce the load on various services of the ad service pipeline since they&rsquo;ll be requested less often and perform fewer computations, which can improve the system&rsquo;s overall performance.\nCaching can also help to reduce the latency, or delay, in the ad delivery process since less I\/Os implies less latency in the process of delivering the ad to the user. This not only improves the user experience but makes ad-serving more competitive in a real-time bidding context and means fewer in-flight requests at any given moment on the infrastructure (less pressure).\nUnfortunately, caching is a complex computer science subject and many papers were published with various algorithms to try to maximize the caching efficiency in a wide variety of contexts. Let&rsquo;s dive into the theory!\nReducing cache misses As the purpose of a cache is to store commonly requested data to be able to serve it faster and reduce computation time or network IOs, the main objective for a cache component is to be able to have the requested data stored as often as it can. In an ideal world, the cardinality of requests (the total number of unique requests) is finite, but in a wide number of applications, it is infinite or just too high for the cache to store every response to every possible request in memory. Given this memory constraint, the challenge is to find the best caching strategy to keep the number of cache misses to a minimum (we call a cache request a miss whenever the entry was to store in the cache, meaning that the cache did not help). We can also measure the cache efficiency the other way around by measuring the number of cache hits (when the cache already has the value for the requested key stored in memory, meaning that no additional I\/Os or computation has to be performed for that operation). This &ldquo;caching strategy&rdquo; is defined by what we call admission\/eviction policies. Hundreds of policies exist nowadays, and this is still as of today a hot research topic.\nCache access patterns As caching is a common practice across all digital systems, there is a wide variety of applications (CPU caches, search engine results, web page contents, &hellip;). This implies that choosing the &ldquo;best&rdquo; caching policies will highly depend on the current context. For this reason, it is crucial to be able to classify cache access patterns.\nLocality of references It turns out that a lot of research has already been conducted in this field. The term [locality of reference was introduced by Peter J. Denning in 2005 in the paper &ldquo;The Locality Principle&rdquo; and is now commonly used in computer science. This Wikipedia article is rather well written and the principle itself is quite general (it&rsquo;s not just about caching) so we won&rsquo;t get into too much detail here, but we can denote a few common cache access patterns from this.\nCommon access patterns This is not an exhaustive listing of all patterns, but rather a possible classification:\nRecency-friendly access patterns When an entry is likely to be accessed multiple times, in a row or almost (in other words, there is a strong locality of reference). In this scenario, a simple cache eviction policy such as LRU (Least Recently Used) works well. We&rsquo;ll dive into actual policies in a future article in this series. Thrashing access patterns When the access pattern is cyclic (repeats over time) Scan\/streaming access patterns When there is little to no locality of reference. It&rsquo;s the opposite of the recency-friendly access pattern. Mixed access patterns When the pattern is a mix of the above. In this scenario, it is often best to benchmark policies as it can become difficult to classify further. Scan resistance Given the common access patterns we&rsquo;ve seen, there is a criterion called scan resistance which is the ability of a cache policy to handle scan patterns without discarding all actual common entries. This is important for mixed access patterns, where a sudden burst of streaming accesses (little to no locality of reference for a duration) can fill up a cache with one-hit entries while discarding the ones that were likely to be requested later. It is important to choose a cache eviction policy that is scan-resistant when there is some scan\/streaming access pattern going on. For instance, the LRU policy (which is the most commonly used policy in general because of how simple the implementation is) is not scan-resistant at all and can become inefficient as the streaming access pattern is prominent.\nKeys cardinality While looking for the best-suited caching policies is important to increase the caching efficiency, a complementary technique is to lower the cardinality of the key fields.\nLet&rsquo;s say we&rsquo;re implementing a caching mechanism for a search engine. Unless you&rsquo;re building the next Google, it&rsquo;s likely that the order of the keywords is not important, thus, why would we consider &ldquo;John Doe&rdquo; to be a different request than &ldquo;Doe John&rdquo;? By considering the two queries the same we end up improving the caching efficiency by a lot. In this example, this could be achieved for instance with a simple sort over the list of keywords.\nHere is a non-exhaustive list of ideas to reduce the cardinality of cache keys:\nIf keys are composed of several inputs (such as words in our example above), does the order matter? If not, then sort them so that keys with the same inputs are always presented the same way to the cache. If keys or one of its inputs is a string, does the case matter? If not, transform them to lowercase every time to reduce cardinality. In the same spirit, you can trim whitespaces or EOL characters. Avoid raw floating values. Floating values are known to be quite &ldquo;volatile&rdquo;. Usually, rounding them to a precision that makes sense can prevent this issue. Depending on the criticality, it is sometimes worth monitoring this cardinality in some ways. That can be done in several ways. For instance, if the keys are made of several distinct inputs, the uniqueness of each input can be computed independently. Lowering the cardinality of the most volatile input may decrease the overall cardinality of the keys.\nFinally, an interesting approach is to AB test different ways to build the keys and measure the impact of each over the efficiency. This can be a bit tricky to set up but that&rsquo;s to my knowledge the easiest and the most efficient way to move forward when keys are complex and the access pattern is mixed.\nEviction policy Have you ever heard or seen this quote: &ldquo;There are only two hard things in Computer Science: cache invalidation and naming things&rdquo;? Either this is a joke or the hard truth, I think the idea behind this is that the hardest things in computer science are non &ldquo;solvable&rdquo; problems. Cache invalidation, like naming things, is difficult because there is no universal solution. It&rsquo;s a matter of context, tradeoffs and even sometimes personal taste.\nA cache invalidation policy (or cache eviction policy) is the logic for invalidating an entry from the cache. Eviction policies can serve multiple purposes, such as invalidating an entry after a given time (for instance an absolute or sliding TTL - Time To Live). When a cache takes too much memory, an eviction policy is required to discard entries whenever the maximum memory allowed (or the maximum number of entries) is reached. Such policies can also be called cache replacement policies. Some commonly used eviction policies for limiting memory usage are LRU (Least Recently Used) or LFU (Least Frequently Used) for instance, however as stated above, this is a complex and broad computer science topic. In this article, we&rsquo;re focused on in-memory caching for microservices and still, in this context, there are plenty of options: every year new scientific papers are published with new ideas and some policies can even be combined (for instance TTL+LRU).\nAdmission policy An admission policy can be used to prevent entries from being stored in the cache given some criteria. For instance, in some applications, you may know in advance that a given entry is unlikely to hit the cache more than once (for a search engine it could be a very long query). Then you may decide to never store such entries (and so no replacement policy would come into play). My advice is to use an admission policy whenever it can apply. If what occupies the most cache memory is the value (compared to keys), then an interesting trick is to still store the keys in the cache when the admission policy prevents the storage of the value. This would have a slight memory overhead because we would store more keys, however, it allows us to keep track of the usage of a given key, making it possible for the admission policy to predict more accurately whether a value is worth storing or not.\nWhich caching policy is the best? The answer is &ldquo;it depends&rdquo;. The ideal policy would be the one that can predict the future to know in advance what is worth storing&hellip; But that&rsquo;s most of the time not possible, so in the end, there is no policy which outperforms others every time. You&rsquo;ll need to analyze access patterns and run benchmarks, and that takes time. However, when you get comfortable with common access patterns](### Common access patterns), you have a rough idea of what kind of policy you want to go for. In a future article in this caching series, we&rsquo;ll run benchmarks over a few common and less common cache replacement policies given various access patterns, hopefully, that will give you some insights as well.\nReducing memory usage We&rsquo;ve seen how understanding the context to choose appropriate policies and bringing cardinality down is key to improving the likelihood of a cache being efficient. However, we intentionally left an important and complementary factor to cache efficiency, which is memory usage. As soon as a cache is constrained to store a limited number of entries or bytes, we know that pushing this limit or optimizing memory usage will increase global efficiency in most scenarios. Adding RAM or storage is a solution but we&rsquo;ll focus on the less obvious solutions (yet more cost-effective and more interesting for the sake of this article).\nKeys as hashes The goal of a cache is to, from a given key, return an associated value without involving the I\/Os or computations normally required, and for that, the cache itself does not need to understand what the key is made of. For this reason, if the key is made of a substantial amount of data, we can have the cache internally store a shortened (but still as uniquely identifiable) version of that key instead of the full key. That&rsquo;s how some high-performance key-value storages do this, such as Aerospike for instance.\nAs it can become a bit cumbersome to deal with hashes on top of the caching middleware, in most languages supporting generics an interesting approach is to internalize this to the cache object. Here is what it would look like in C#:\n\/\/\/ A cache that would store key public interface Cache&lt;Key, Value&gt; { bool TryGetValue(Key key, Func&lt;Key, Value&gt; valueFactory, out Value value); } \/\/\/ A cache that store hashed keys, thus being more memory efficiency when keys are large objects public interface Cache&lt;Key, Hash, Value&gt; { bool TryGetValue(Key key, Func&lt;Key, Hash&gt; hashFactory, Func&lt;Key, Value&gt; valueFactory, out Value value); } This optimization can become quite powerful depending on the nature of the keys. Let&rsquo;s say we&rsquo;re caching search engine queries: on average, a key might be composed of 20 UTF-16 characters, representing 320 bits of data. Transforming this key to a 128-bit hash digest will divide by more than 2 the memory required for the keys part, thus making room for storing more entries and improving cache efficiency.\nAnother benefit of such an approach is that keys of variable size are usually either individually stored on the heap or require an oversized buffer. With hashes of a fixed size, memory can be much more compact, which will reduce the CPU workload for several reasons. At Equativ, we have implemented a structure called Hash128 to generate hashes from keys of any kind. It turns out Unity (the 3D engine) has also recently implemented a similar API (with the same name!). Part of their implementation can be found here on Github. It can serve as a nice basis to understand how they do it but I wouldn&rsquo;t recommend copying any of this for licensing reasons obviously but also because I find it flawed in some ways (mutable structs = \u26a0\ufe0f). If you are interested in our implementation, don&rsquo;t hesitate to ask us in the comments and we&rsquo;ll try to make a dedicated article on it, we think it can have many usages and is worth sharing \ud83d\ude04.\nA word on collisions According to the pigeonhole principle, given that input data is usually more than 128bit (otherwise there is no point in doing this optimization technique), collisions-free is not guaranteed. However, in practice, the likelihood hood to have a single collision is very low (about 1% chance of collision for 2,600,000,000,000,000,000 generated hashes with a good hashing algorithm). At Equativ, we haven&rsquo;t noticed a single collision, however, I wouldn&rsquo;t recommend this optimization if a single collision can have critical consequences.\nValue duplicates In some cases, a cache can store several times the same value for different keys. As this percentage of duplicated values and the average value size increases, storing values once and storing references\/pointers can make a big difference in memory usage, as we can see with this interactive visualization. As for storing keys, this optimization does not always make sense, so once again it is important to understand the context to avoid doing additional lookups and storing additional pointers for no reason.\nReducing memory fragmentation Here I decided to talk about memory fragmentation as part of a whole different section. As we&rsquo;ve seen storing hashed keys might not only help reduce memory usage but might also help reduce memory fragmentation depending on what the keys are. Memory fragmentation is a crucial performance indicator yet often overlooked given how difficult it can be to measure\/observe it, as opposed to memory usage.\nArena-based linked list Most cache eviction policies (actually, all that I can think of) require the usage of one or more doubly linked lists to achieve true O(1) operations since such data structures allow O(1) removals and O(1) insertions while keeping order. Unfortunately, in Rust, Dotnet, Python, Java and probably many other languages, base libraries include a doubly linked list implementation where a node is an object individually allocated on the heap. This will inevitably imply a lot of allocations\/deallocations and memory fragmentation.\nThere is however a possible alternative, which we call arena-based linked lists. In short, as opposed to allocating nodes individually on the heap, we allocate one continuous buffer. The base principle came to us when we looked at how dotnet base Dictionary&lt;K, V&gt; class handles new entries with fields keeping track of free slots. For our linked list implementation, when the buffer is allocated, even if there is room for 1000 nodes but only 10 are actually used, we keep behind the scenes 990 &ldquo;free&rdquo; nodes linked together. Then, when a new entry is added to the list, we simply have to pick the first free entry at O(1) cost without having to allocate anything (unless the buffer is too small and needs to be resized). This is kind of having a linked list within our linked list for tracking free nodes. Thanks to this, we are now able to implement eviction policies with minimal allocations, less fragmentation, and better CPU affinity.\nIn case you are interested or just curious, here is an open-sourced version of that linked list implementation. You can see how the CPU times and allocations compare with the one from the Dotnet BCL:\n| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated | |------------------ |-----------:|----------:|----------:|-------:|-------:|-------:|----------:| | AddFirstBCL | 102.818 ns | 2.0356 ns | 3.5651 ns | 0.0080 | 0.0029 | 0.0004 | 48 B | | AddFirstOptimized | 6.527 ns | 0.1034 ns | 0.0808 ns | - | - | - | - | | AddLastBCL | 101.499 ns | 1.2358 ns | 1.1560 ns | 0.0080 | 0.0029 | 0.0004 | 48 B | | AddLastOptimized | 6.476 ns | 0.1129 ns | 0.1056 ns | - | - | - | - | What&rsquo;s next? We went through the most important factors to take into account when setting up a cache. With this, we should be able to analyze a given use case by asking ourselves a few questions:\nIs it part of a critical path? How much memory space is available? What&rsquo;s the access frequency? How can we qualify the access pattern? From that, we can make an informed choice in picking a cache eviction policy implementation that is well-suited. In the next article, we&rsquo;ll see what exists in the literature, break down implementation details to better understand their strength and weaknesses, how to combine them, and finally compare them in some real-world scenarios.\n","permalink":"https:\/\/ogxd.github.io\/articles\/caching-01-challenges-and-memory-considerations\/","summary":"In this article I&rsquo;d like to share my journey learning about caching, and my research on how to make it more efficient. This article is the first in a serie of articles about caching, and here we&rsquo;ll start by discussing the challenges and memory considerations when doing in-memory caching.\nThis was done as part of my day job as a Staff backend engineer at Equativ, a leading provider of digital advertising solutions, offering a range of products and services to help businesses reach their target audiences and achieve their marketing goals.","title":"Challenges & memory considerations for in-memory caching"},{"content":"Tracing is a telemetry concept that gives us the big picture of what happens when a request is made on a distributed system.\nSeveral solutions exist to add &ldquo;automated&rdquo; tracing. Abstracting and hiding things away from you does indeed make it easier to use, but as soon as you need to adapt something to your specific needs, it will start to be a pain. If you have the human resources and the will to have a proper tracing, my advice is to understand the concepts and implement parts of it yourself. The OpenTelemetry defines standards, semantics, and protocols and provides some libraries and tools to help you with that.\nIn this article, I&rsquo;ll share my experience 2 years after starting to implement at scale, in a backend handling hundreds of billions of requests per day, and more specifically in .NET.\nThe .NET Activity API Since .NET 6, the Activity API (System.Diagnostics) serves as a built-in and platform-agnostic way to record a trace.\nWhile the Activity API namings sometimes differ from the OpenTelemetry ones, the concepts are the same.\nHere is a non-exhaustive mapping table:\nActivity API OpenTelemetry Comment Activity Span Activity Tag Span Attribute Missing Span Resource OpenTelemetry .NET libraries add resources alongside what activities holds when creating spans. Activity Baggage Missing I don&rsquo;t recommend using Activity Baggages at all since there isn&rsquo;t really any equivalent on the Opentelemetry side. Activity DisplayName Span Name How It Works This API is a little uncommon, to say the least. I&rsquo;ll spare you the details. To make it simple, it works with 3 components:\nActivity: The equivalent of a Span in OpenTelemetry. It represents a unit of work. ActivitySource: It&rsquo;s used to create Activities. ActivityListener: It&rsquo;s used to receive callbacks when Activities are created, started, stopped, etc. Example \u2192 Listening to Activities\n\/\/ Create a source &#34;MySource&#34; ActivitySource activitySource = new(&#34;MySource&#34;); \/\/ Create a listener ActivityListener activityListener = new() { \/\/ This listener only listens to Activities created by sources with name &#34;MySource&#34; ShouldListenTo = source =&gt; source.Name == activitySource.Name, \/\/ Any Activity it listens to is marked as &#34;AllDataAndRecorded&#34; Sample = (ref ActivityCreationOptions&lt;ActivityContext&gt; _) =&gt; ActivitySamplingResult.AllDataAndRecorded \/\/ Receive callbacks to know when a listened Activity is started or stopped ActivityStarted = activity =&gt; Console.WriteLine($&#34;Activity {activity.OperationName} started&#34;) ActivityStopped = activity =&gt; Console.WriteLine($&#34;Activity {activity.OperationName} stopped&#34;) }; \/\/ Register the listener (yes this is statis \ud83d\ude44) ActivitySource.AddActivityListener(activityListener); \/\/ Then anywhere in your code, you can create an Activity var activity = activitySource.StartActivity(&#34;Activity&#34;); \/\/ StartActivity automatically sets the Current Activity Assert.AreEqual(Activity.Current, activity); \/\/ Activity is not null because it&#39;s listened by at least one listener Assert.NotNull(activity); \/\/ Activity is marked as recorded because the listener sets it as &#34;AllDataAndRecorded&#34; Assert.IsTrue(activity.Recorded); Here you can see that you can, with a few tweaks on this example:\nListen to sources you are interested in in the ShouldListenTo callback. Implement a sampling logic in the Sample callback Implement the logic to convert the Activity to an OpenTelemetry Span in the ActivityStopped callback and send it (in batches) to your observability backend. Existing Activity Sources The source named &ldquo;Microsoft.AspNetCore&rdquo; is used by ASP.NET Core to create Activities for incoming HTTP requests. The source named &ldquo;System.Net.Http&rdquo; is used by HttpClient to create Activities for outgoing HTTP requests. Third-party libraries that are up-to-date with tracing will usually define their own ActivitySource and create Activities for their operations. Unfortunately, not all libraries are up-to-date with tracing, and you might have to create your own ActivitySource and create Activities for their operations, sometimes requiring you to monkey-patch the library or make wrappers around it \ud83d\ude22.\nFortunately, the OpenTelemetry for .NET packages helps you in this situation with what they call &ldquo;instrumentation&rdquo;. An example is the SQL instrumentation where they listen to diagnostics events (a different piece of tech than the Activity API) emitted from Microsoft.Data.Sql. Hopefully one day more libraries will (properly) implement tracing, and we won&rsquo;t have to rely on third parties to do it for us.\nThe OpenTelemetry .NET Libraries OpenTelemetry has open-sourced a set of libraries to help you with tracing in .NET: https:\/\/github.com\/open-telemetry\/opentelemetry-dotnet.\nThey aim to help listen to several sources, simplify setup via DI extensions, and provide exporters to send the traces to your observability backend.\nIn my personal opinion, the libraries are still a bit rough around the edges, and you might end up complexifying your code instead. I recommend using the exporters and some instrumentation packages if not trivial to implement yourself, such as the one for Microsoft.Data.Sql.\nAsyncLocal Magic The Activity API uses AsyncLocal&lt;T&gt; to store the current Activity. AsyncLocal&lt;T&gt; is a powerful construct, but it&rsquo;s also a bit of a black box for the uninitiated. It&rsquo;s an async-context-local storage that works with async\/await. What makes it very interesting in the context of tracing is that it allows you to create Activities that are bound to an async context without having to refactor all of your code to pass the Activity around. You just use it as if it was a global variable.\nExample \u2192 Creating Activities in async code\nActivity.Current = source.StartActivity(&#34;A&#34;); await DoWorkAsync(); Console.WriteLine(Activity.Current.OperationName); \/\/ &#34;A&#34; static async Task DoWorkAsync() { Activity.Current = source.StartActivity(&#34;B&#34;); await SetThirdValueAsync(); Console.WriteLine(Activity.Current.OperationName); \/\/ &#34;B&#34; } static async Task DoMoreWorkAsync() { Activity.Current = source.StartActivity(&#34;C&#34;); await Task.Delay(1000); Console.WriteLine(Activity.Current.OperationName); \/\/ &#34;C&#34; } It is very powerful, but it can also be unintuitive for the non-initiated. Here is an example of a pitfall: https:\/\/x.com\/MrPeterLMorris\/status\/1763502114184053198?s=20\nWhen to Create Activities? Tracing is meant to get a &ldquo;big picture&rdquo; of a distributed system. In this context, while it can be tempting to create an Activity for every method call, I think it&rsquo;s not a good idea. My rule of thumb is to have traces depend on architecture but not code. My advice is to create an Activity only in such cases:\nAn incoming I\/O, such as a request received in an ASP NET Core service. This way you have the server-side spans. An outgoing I\/O, such as an HTTP request sent by an HttpClient, or an SQL query. This way you want client-side spans. With client-side and server-side spans and tracing implemented across all services, you can create a map of your services and pinpoint complex issues in distributed systems, such as answering where the latency is coming from.\nExceptionally, it can make sense to have an Activity for some &ldquo;internal&rdquo; asynchronous operations. For instance, a buffering middleware may introduce latency, but it is not per se considered an outgoing I\/O (or difficult to consider as such).\nSampling Sampling is maybe one of the most complex aspects of tracing. It&rsquo;s the process of deciding which traces to keep and which to discard. It&rsquo;s a trade-off between the amount of data you want to collect and the performance overhead of collecting it.\nThere are two types of sampling:\nHead-based sampling: the decision to sample is made at the beginning of the trace. Tail-based sampling: the decision to sample is made at the end of the trace. Tail-based sampling implies that every trace must be built and stored in memory before the decision to sample is made. This is not efficient and can lead to memory issues. Also, tail-based sampling implies that a trace might be sampled depending on some criteria, which would make the traces as a whole not representative of the whole traffic.\nThere is a nice write-up on the OpenTelemetry website about sampling: https:\/\/opentelemetry.io\/docs\/concepts\/sampling\/. However, it can be a bit overwhelming. I think what they call &ldquo;Consistent Probability Sampling&rdquo; is the best approach to sampling for the majority of use cases, but their implementation proposal is overly complex IMHO, so I&rsquo;ll propose my own.\nConsistent Probability Sampling Because tracing is distributed, it implies that the sampling decision but be consistent across all services taking part in the trace. We could pass a sampling decision from one service to the next, but it implies that the first service would need to know it is indeed the first service in the trace, which can add some complexity. Instead, we chose to use consistent probability sampling.\nConsistent probability sampling means that the sampling decision is made based on the trace ID and some constant sampling rate. This means that the same trace ID will always be sampled or not sampled, no matter the service. This is achieved by using a hash of the trace ID and the sampling rate.\nThe hashing must be ubiquitous across all services so that the same trace ID will always be sampled or not sampled. This is why we chose to use the FNV-1a hash function, which is a non-cryptographic hash function that is easy to implement and is widely used in distributed systems and which should be sufficient for our use case. The trace ID must be uppercased before being hashed.\nExample \u2192 FNV-1a-based sampling in C#\npublic static bool Sample(string traceId, uint samplingRate) { uint h = 0x811c9dc5; for (var i = 0; i &lt; traceId.Length; i++) { h ^= traceId[i]; h *= 16777619u; } return h % samplingRate == 0; } public static void Main() { Console.WriteLine(Sample(&#34;A12C78D8&#34;, 2)); \/\/ False Console.WriteLine(Sample(&#34;7129034239FCB&#34;, 2)); \/\/ True } Bypassing The Sampling In some cases, we might want to bypass the sampling. For example, when we are debugging a specific request, or for test automation purposes, we might want to see to force the sampling for a trace.\nThe W3C defines a &ldquo;sampling flag&rdquo; for the traceparent header: https:\/\/www.w3.org\/TR\/trace-context\/#sampled-flag. However, I think relying on it can have collateral effects. For instance, if a B2B customer calls your API with the flag set because he uses tracing on his side, it will force the trace to bypass the sampling on your side.\nI prefer using the tracestate header with a value such as no-sampling for my vendor name my-vendor. Then I can look for this value in my Sample delegate and bypass the sampling if it&rsquo;s present.\nExample \u2192 tracestate: my-vendor=no-sampling,other-vendor=whatever\nContext propagation Context propagation is what makes tracing distributed: it&rsquo;s the process of passing the trace context from one service to the next. See the OpenTelemetry documentation about context propagation: https:\/\/opentelemetry.io\/docs\/concepts\/context-propagation\/.\nIn .NET, the Activity class has a Context property that holds the trace context. The OpenTelemetry .NET libraries provide &ldquo;Propagators&rdquo; to automatically copy the context into HTTP headers when making outgoing HTTP requests, and to extract the context from incoming HTTP requests. It&rsquo;s nice, but you may not want to inject these headers in every request you perform (EG you call a third-party API, they don&rsquo;t need your tracing headers). Also, it will only work for HTTP requests, which is far from covering all the I\/Os you might have in your system (gRPC + protobuf, RabbitMQ, Kafka, &hellip;).\nIn my opinion, the best way to propagate the context is to do it manually. You can use the Activity.Current.GetW3CTraceParent() extension method I provided at the end of this article to get a string that complies with the W3C traceparent header format. Then you can pass this string to the next service in the request, either as a header or in any other form for protocols not covered by OpenTelemetry specifications. The tracestate header can be read as is from Activity.Current.TraceStateString.\nBonus I&rsquo;d like to share some resources that I found useful when implementing tracing in .NET.\nUseful Extensions \/\/ Extension to check if an Activity is sampled before adding tags or events (avoid unecessary work and allocations in case trace is going to be discarded). public static bool IsRecorded([NotNullWhen(true)] this Activity? activity) { return activity != null &amp;&amp; activity.Recorded; } \/\/ Extension to start an &#34;internal&#34; activity (no I\/Os). Automatically picks the name of the caller class and method. public static Activity StartActivityInternal(this ActivitySource source, [CallerFilePath] string callerFilePathAttribute = &#34;&#34;, [CallerMemberName] string callerMemberName = &#34;&#34;) { var activity = source.StartActivity(ActivityKind.Internal); if (activity.IsRecorded()) { string fileName = Path.GetFileNameWithoutExtension(callerFilePathAttribute); activity.DisplayName = $&#34;{fileName}.{callerMemberName}&#34;; } return activity; } \/\/ Extension to start an &#34;external&#34; activity (involving I\/O). Sets a bunch of OpenTelemetry tags to help the tracing backend understand the context and display it properly. public static Activity StartActivityExternal(this ActivitySource source, string serviceName, string operationKind, bool isDatabase = false) { var activity = source.StartActivity(operationKind, ActivityKind.Client); if (activity.IsRecorded()) { \/\/ This is a special tag, see https:\/\/github.com\/open-telemetry\/opentelemetry-specification\/blob\/6ce62202e5407518e19c56c445c13682ef51a51d\/specification\/trace\/semantic_conventions\/span-general.md#general-remote-service-attributes activity.SetTag(&#34;peer.service&#34;, serviceName); if (isDatabase) { \/\/ This is a special tag, see https:\/\/github.com\/open-telemetry\/opentelemetry-specification\/blob\/6ce62202e5407518e19c56c445c13682ef51a51d\/specification\/trace\/semantic_conventions\/database.md#connection-level-attributes activity.SetTag(&#34;db.system&#34;, serviceName); } } return activity; } \/\/ Extension a string that complies with the W3C traceparent header format public static string GetW3CTraceParent(this Activity activity) { return $&#34;00-{activity.Context.TraceId}-{activity.Context.SpanId}-{(byte)activity.Context.TraceFlags:x2}&#34;; } \/\/ Extension to set an Activity in an error state public static void SetError(this Activity activity, Exception exception, string message = &#34;&#34;) { string description = string.IsNullOrEmpty(message) ? string.Empty : $&#34;{message}. &#34;; description += $&#34;Exception: {exception}&#34;; \/\/ Extension method from OpenTelemetry libraries that sets some tags activity.SetStatus(Status.Error.WithDescription(description)); \/\/ Specific to the Activity API activity.SetStatus(ActivityStatusCode.Error, description); } Useful Links Grafana Tempo. A distributed tracing backend that is easy to set up and use. Available as a self-hosted solution (open source) or as a managed service (paid). In my opinion, it is the best tracing backend available and follows OpenTelemetry specifications quite well. The TraceQL language is very powerful. It does take some time to set up and learn however. opentelemetry.io. Always a good starting point for learning about tracing. Article on hidden working of AsyncLocal and ExecutionContext by Nakib. A good read to understand the magic behind AsyncLocal&lt;T&gt; and ExecutionContext. ","permalink":"https:\/\/ogxd.github.io\/articles\/implementing-tracing\/","summary":"Tracing is a telemetry concept that gives us the big picture of what happens when a request is made on a distributed system.\nSeveral solutions exist to add &ldquo;automated&rdquo; tracing. Abstracting and hiding things away from you does indeed make it easier to use, but as soon as you need to adapt something to your specific needs, it will start to be a pain. If you have the human resources and the will to have a proper tracing, my advice is to understand the concepts and implement parts of it yourself.","title":"My experience on implementing tracing at scale"},{"content":"While developing GxHash over my spare time during my last parent leave (babies sleep a lot, I swear I&rsquo;m a good father \ud83d\ude07), I went down the rabbit hole and came up with increasingly low-level optimizations. In this article, I want to talk about one of the nastiest ones, but to whom GxHash is owed to be the fastest non-cryptographic hashing algorithm up to this date.\nI called this optimization \ud83e\udd41\ud83e\udd41\ud83e\udd41 &ldquo;Unsafe Read Beyond of Death&rdquo; (or URBD).\nTo achieve maximum performance, one of the design goals of GxHash was to use SIMD instructions as much as possible. SIMD instructions are a set of instructions that allow a single instruction to operate on multiple data elements in parallel. In practice, with a single SIMD instruction operating on 16 or even 32 bytes of data at once, input data would be required to be a multiple of 16 or 32 bytes, but in practice, inputs are of arbitrary lengths. Other highly-optimized hashing algorithms that rely on SIMD usually process the uneven part with scalar instructions, which is slower and implies special handling (thus more instructions).\nFor GxHash, I decided to avoid such scalar operations and load this uneven part into a 16 bytes zero-padded SIMD register. A simple and safe way to do this is to copy the uneven part into a zero-initialized temporary buffer, and then load this buffer into a SIMD register.\n#[cfg(target_arch = &#34;x86_64&#34;)] use core::arch::x86_64::*; pub type State = __m128i; #[inline(always)] pub unsafe fn get_partial_safe(data: *const State, len: usize) -&gt; State { \/\/ Temporary buffer filled with zeros let mut buffer = [0i8; VECTOR_SIZE]; \/\/ Copy data into the buffer std::ptr::copy(data as *const i8, buffer.as_mut_ptr(), len); \/\/ Load the buffer into a __m256i vector return _mm_loadu_si128(buffer.as_ptr() as *const State); } This worked well and simplified the code a lot by allowing a generalization of the hashing logic to only operate on 16 bytes chunks. However, this approach has a performance cost: the copy operation. While GxHash still outperformed other hashing algorithms for large payloads, the copy operation was a huge bottleneck for small payloads. A reason for this is that the algorithm was very CPU cache friendly while this single copy operation was reading from RAM, which is orders of magnitude slower.\nRead beyond madness To avoid this copy operation, I decided to experiment with reading beyond the end of the input buffer. This is a very dangerous operation, as you don&rsquo;t know what&rsquo;s beyond the end of the buffer. The OS may throw a SIGSEGV at your face and terminate your process. Let&rsquo;s try it anyway&hellip;\n#[cfg(target_arch = &#34;x86_64&#34;)] use core::arch::x86_64::*; pub type State = __m128i; #[inline(always)] pub unsafe fn get_partial_unsafe(data: *const State, len: usize) -&gt; State { return _mm_loadu_si128(data); \/\/ \u2620\ufe0f } Using this instead of copying, we have a more than x10 speedup for small payloads. Of course, we&rsquo;re far from done as this code will hash bytes that don&rsquo;t belong to our stream and also eventually crash the program. But we might have something.\nSanitizing &ldquo;Safe&rdquo; read beyond A trick to avoid reading beyond the end of the buffer is to make sure the end of the buffer lies on the same page. Typically, the OS will allocate memory in pages of 4KB, thus we can make a function that checks whether it is okay to read beyond or if we should fallback to the copy version.\n#[inline(always)] unsafe fn check_same_page(ptr: *const State) -&gt; bool { let address = ptr as usize; \/\/ Mask to keep only the last 12 bits let offset_within_page = address &amp; (PAGE_SIZE - 1); \/\/ Check if the 16nd byte from the current offset exceeds the page boundary offset_within_page &lt; PAGE_SIZE - VECTOR_SIZE } Considering a page size of 4096 bytes, the likelihood of having 32 bytes on the same page exceeds 99%. This safety check is cost-effective, retaining most performance benefits while ensuring safety.\nSIMD Masking We can now read beyond safely, but we still need to mask the bytes that don&rsquo;t belong to our stream. Again, we want to use SIMD instruction to do this, or it&rsquo;ll defeat the purpose of the optimization. A trick is to create a constant vector of consecutive bytes and compare it to the length of the stream. That would return us a mask that we can apply to the vector.\n#[inline(always)] pub unsafe fn get_partial_unsafe(data: *const State, len: usize) -&gt; State { let indices = _mm_set_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); \/\/ Create a mask by comparing the indices to the length let mask = _mm_cmpgt_epi8(_mm_set1_epi8(len as i8), indices); \/\/ Mask the bytes that don&#39;t belong to our stream return _mm_and_si128(_mm_loadu_si128(data), mask); } Mixing length back into the equation We&rsquo;re not done yet. As we read N bytes into a 16 bytes vector, we kind of lost the context of the length of that uneven part.\nFor instance, let&rsquo;s say our input data is a blob of 7 bytes, like so:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 0x01 42 08 7A 89 10 00 ?? ?? ?? ?? ?? ?? ?? ?? ?? We read this into a 16 bytes vector, and we mask the bytes that don&rsquo;t belong to our stream:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 0x01 42 08 7A 89 10 00 00 00 00 00 00 00 00 00 00 But what if the input is now a blob of 6 bytes?\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 0x01 42 08 7A 89 10 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? We would read this into a 16 bytes vector, and we mask the bytes that don&rsquo;t belong to our stream:\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 0x01 42 08 7A 89 10 00 00 00 00 00 00 00 00 00 00 The result is the same as the previous one, while the input was different (this one had one more 0x00). This is a problem, as we want to make sure that the length of the input is taken into account.\nA trick is to wrap-add the length of the uneven part to every byte of the masked vector. This way, the masked bytes will be different for different lengths of the input.\nRead the uneven part first A complementary trick to this optimization is to read the uneven part first, and then read the 16 bytes chunks. For inputs greater than 16 bytes, it means we can assume it&rsquo;s safe to read beyond the end of the buffer since there will be more bytes to read after. This enables us to skip the safety check in this specific scenario.\nPutting it all together Here is the final code for the URBD optimization:\n#[cfg(target_arch = &#34;x86_64&#34;)] use core::arch::x86_64::*; pub type State = __m128i; #[inline(always)] pub unsafe fn get_partial(p: *const State, len: usize) -&gt; State { \/\/ Safety check if check_same_page(p) { get_partial_unsafe(p, len) } else { get_partial_safe(p, len) } } #[inline(always)] unsafe fn check_same_page(ptr: *const State) -&gt; bool { let address = ptr as usize; \/\/ Mask to keep only the last 12 bits let offset_within_page = address &amp; (PAGE_SIZE - 1); \/\/ Check if the 16nd byte from the current offset exceeds the page boundary offset_within_page &lt; PAGE_SIZE - VECTOR_SIZE } \/\/ Fast path #[inline(always)] pub unsafe fn get_partial_unsafe(data: *const State, len: usize) -&gt; State { let indices = _mm_set_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); \/\/ Create a mask by comparing the indices to the length let mask = _mm_cmpgt_epi8(_mm_set1_epi8(len as i8), indices); \/\/ Mask the bytes that don&#39;t belong to our stream let partial_vector = _mm_and_si128(_mm_loadu_si128(data), mask); \/\/ Wrap-add the length of the uneven part to every byte of the masked vector _mm_add_epi8(partial_vector, _mm_set1_epi8(len as i8)) } \/\/ Fallback #[inline(always)] pub unsafe fn get_partial_safe(data: *const State, len: usize) -&gt; State { \/\/ Temporary buffer filled with zeros let mut buffer = [0i8; VECTOR_SIZE]; \/\/ Copy data into the buffer std::ptr::copy(data as *const i8, buffer.as_mut_ptr(), len); \/\/ Load the buffer into a __m256i vector let partial_vector = _mm_loadu_si128(buffer.as_ptr() as *const State); _mm_add_epi8(partial_vector, _mm_set1_epi8(len as i8)) } Some results! Here is the same benchmark including the URBD optimization. The chart is log-scaled in both X and Y. You can see that GxHash is now the fastest non-cryptographic hashing algorithm even for small payloads, and by quite a margin.\nThe numbers:\nThroughput (MiB\/s) 4 8 16 32 64 gxhash 6292.82 12605.37 25252.22 29296.83 40690.10 xxhash 1594.03 3166.81 6465.02 11452.38 16961.84 ahash 1247.40 2482.24 4972.79 7312.82 8663.48 t1ha0 1221.45 2442.69 4457.48 8174.15 10766.91 seahash 1160.73 2547.56 4480.69 7054.78 9047.05 metrohash 612.20 1223.72 2225.81 4445.55 7768.96 highwayhash 189.08 390.12 768.08 1692.98 2780.67 fnv-1a 2042.93 2455.40 2715.25 2083.61 1462.05 Source code for the algorithm and benchmarks can be found on the GxHash repository!\n","permalink":"https:\/\/ogxd.github.io\/articles\/unsafe-read-beyond-of-death\/","summary":"While developing GxHash over my spare time during my last parent leave (babies sleep a lot, I swear I&rsquo;m a good father \ud83d\ude07), I went down the rabbit hole and came up with increasingly low-level optimizations. In this article, I want to talk about one of the nastiest ones, but to whom GxHash is owed to be the fastest non-cryptographic hashing algorithm up to this date.\nI called this optimization \ud83e\udd41\ud83e\udd41\ud83e\udd41 &ldquo;Unsafe Read Beyond of Death&rdquo; (or URBD).","title":"Unsafe read beyond of death"},{"content":"Many languages and frameworks have been designed to make developers more productive. This is a good thing, but it has a side effect: it makes developers less aware of the performance implications of their code.\nWhile hardware has been getting faster and faster over the years, the place software has taken in our lives has also been growing. In the end, the performance of the code we write is still important, and it&rsquo;s important to know when to care about it (and when not to).\nI won&rsquo;t revive traumas of the past and talk about big O time and space complexity, nor I will serve you a &ldquo;premature optimization is the root of all evil&rdquo; bullshit.\nThe pressure of delivering performant code in a culture of productivity can be very frustrating, and so here I am going to give you an easy and pragmatic approach to knowing when to care about performance, and when not to, so you can all be productive and happy developers \ud83d\ude0a.\nTL;DR; for lazy readers When planning a development, think about how often (roughly) the resulting code will be invoked.\nIf the code isn&rsquo;t going to be invoked often, then you don&rsquo;t necessarily need to care about performance. Keep it simple, and focus on readability, maintainability and testability. If the code is going to be invoked often, then you should care about performance (the more often the more you should). Plan some extra time for benchmarking, optimization passes and profiling in the real world. Time is money The performance of the code developers write is roughly proportional to the time they spend on it. Experience may modulate this relationship, but it&rsquo;s still a good rule of thumb.\nUnless you&rsquo;re only programming for fun, it&rsquo;s more than likely that you are writing code for a few bucks, and most likely you&rsquo;re paid based on time. This means it is expected for you to be productive, thus limiting the time you can spend coding a given feature.\nGiven this limited time, the level of optimization of the code you&rsquo;re about to ship is going to be limited as well. This is why it&rsquo;s important to know when to care about performance, and when not to, and only then estimate the time you&rsquo;re going to spend on it.\nWhen to care about performance? Here is the dreaded question. I&rsquo;ll spare you the &ldquo;it depends&rdquo; answer, as I think I have a very systemic and pragmatic approach to answering it.\nJust ask yourself those two questions:\nHow often is the code going to be invoked? How likely is it to change in the future? Frequency I think that&rsquo;s the most important question to ask. The more often a piece of code is going to be invoked, the more you should care about its performance. Sounds obvious, right?\nYou don&rsquo;t have to know exactly how often the code you&rsquo;re about to write is going to be invoked. You often can tell by the nature of the feature and system you&rsquo;re working on. For instance, a piece of code that is going to be invoked for every incoming request on a web service is likely to be invoked a lot, while a piece of code that is going to be invoked only once when the application starts is likely to be invoked less often.\nLike combinatorial explosion, the invocation frequency for a piece of code can escalate quickly. For instance, a feature that checks X business rules for every incoming request on a web service that receives Y requests per second per instance, with Z instances, is going to be invoked about X * Y * Z times per second. With 1000 rules, 1000 rps and 1000 instances, that&rsquo;s 1 billion invocations per second.\nAt 1 billion invocations per second, a piece of code that only takes 1\u00b5s of CPU time is going to take 1,000s of CPU time per second or 1,000 full CPU cores. If we consider a power consumption of 10W per core, that&rsquo;s 10,000W or power consumption, or 87,600kWh per month. At $0.25 per kWh (current price in France), that&rsquo;s $21,900 per month \ud83d\udcb8.\nAllocations-wise, a single memory allocation in this path is going to generate 1 million allocations per second per instance, which is likely to generate a lot of pressure on the garbage collector, thus increasing the latency of the service \ud83d\udc0c.\nEnvironmentally speaking, it&rsquo;s not too good either \ud83d\ude35.\nPut in perspective, it might be interesting to spend a few days optimizing this piece of code.\nOn the other hand, if the code is called at startup, is intended for internal tooling, or is behind a heavily sampled path, then it&rsquo;s likely called not so frequently, and you should not spend too much time optimizing it and rather focus on readability, maintainability and testability.\nVolatility (a.k.a. &ldquo;code churn&rdquo;) Optimization does not necessarily mean increased complexity: often, simplicity is the key to performance. Still, we can&rsquo;t deny that once the simplicity card has been played, the next optimization levers can imply more complex data structures, exotic algorithms, or unsafe code to name a few. This can make a piece of code more complex to grasp, maintain and evolve.\nFor this reason, it&rsquo;s important to consider the volatility of the code. If the code is going to be modified often, then you should be more cautious about the trade-offs you make.\nFor instance, a new business feature is likely to receive a lot of changes, so you may want not to go too deep while optimizing. On the other hand, a change on the logging stack is less likely to change (given its company-internal nature and the fact that logging is a well-defined practice), thus is more appropriate to use more complex optimization techniques in this context.\nSo what then? Well, if you&rsquo;ve estimated that the code you&rsquo;re about to write isn&rsquo;t going to be invoked often, you&rsquo;re free to focus on using what you&rsquo;re the most comfortable with, and what is the most readable, maintainable and testable for your team. As your software evolves and your business grows, at some point, you might have to revisit the code you&rsquo;ve written and optimize it, but unless you knew it in advance, you shall not feel guilty about it and can leave this to the future you or your successors. If you have doubts, you can always instrument your code to measure its performance\/invocation frequency and come back to it later.\nOtherwise, it depends on how often is going to be invoked and how likely this code is to evolve in the future. Benchmark, optimize, profile, and iterate. Ask your peers for help if you&rsquo;re stuck, ask for feedback when you think you&rsquo;ve started pulling some unusual tricks, and test your code in the real world.\nAnd more importantly, don&rsquo;t forget to have fun! \ud83d\ude0a\n","permalink":"https:\/\/ogxd.github.io\/articles\/when-to-care-about-performance\/","summary":"Many languages and frameworks have been designed to make developers more productive. This is a good thing, but it has a side effect: it makes developers less aware of the performance implications of their code.\nWhile hardware has been getting faster and faster over the years, the place software has taken in our lives has also been growing. In the end, the performance of the code we write is still important, and it&rsquo;s important to know when to care about it (and when not to).","title":"When to care about performance"}]