<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 0x48core on Medium]]></title>
        <description><![CDATA[Stories by 0x48core on Medium]]></description>
        <link>https://medium.com/@0x48core?source=rss-914a8bc5f029------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YgzvELnS0sovTe-m1o-Aug.jpeg</url>
            <title>Stories by 0x48core on Medium</title>
            <link>https://medium.com/@0x48core?source=rss-914a8bc5f029------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:24:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@0x48core/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cache Stampede Prevention in Go — 1k req/s load test + full monitoring stack]]></title>
            <link>https://medium.com/@0x48core/cache-stampede-prevention-in-go-1k-req-s-load-test-full-monitoring-stack-68865490c2bc?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/68865490c2bc</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[stampede]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Mon, 11 May 2026 10:59:39 GMT</pubDate>
            <atom:updated>2026-05-11T10:59:39.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 What I built</h3><p>A production-ready cache stampede prevention library in Go with 3 strategies, full Prometheus metrics, and a live Grafana dashboard.</p><h3>🔥 The problem</h3><p>When a hot cache key expires, thousands of concurrent requests all miss at the same time and hammer the database. This is a cache stampede — and it can take down your DB.</p><h3>🛡️ 3 strategies implemented</h3><h3>1. Hard Lock + Stale-While-Revalidate</h3><ul><li>Only one process fetches the new value (Redis SETNX + Lua atomic script)</li><li>Everyone else gets served the stale value immediately — zero wait time</li></ul><h3>2, XFetch (probabilistic early refresh)</h3><ul><li>Formula: P = exp(-β × timeRemaining / δ)</li><li>Starts refreshing in the background before the key expires</li><li>No thundering herd because refreshes are spread out probabilistically</li></ul><h3>3. Request Coalescing (singleflight)</h3><ul><li>In-process deduplication: 50 concurrent goroutines → 1 real DB call</li><li>~13:1 dedup ratio visible in Grafana</li></ul><p>— -</p><h3>📊 Monitoring stack</h3><ul><li>Prometheus metrics for every decision point (hit/miss/stale/lock_contention)</li><li>Grafana dashboard with 9 panels auto-provisioned via docker-compose</li><li>Circuit Breaker state transitions (Closed → Open → Half-Open) tracked as gauges</li><li>Load test drives 1 000 req/s of sustained traffic</li></ul><p>— -</p><h3>🧱 Tech stack</h3><p>Go 1.2x· Redis 7 · Prometheus · Grafana · Docker Compose</p><p>Please give me a star for my repository if it is useful for you. Thanks</p><p>🔗 GitHub: <a href="https://github.com/0x48core/go-latency/tree/main/cache-stampede">[https://github.com/0x48core/go-latency/tree/main/cache-stampede</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68865490c2bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PromQL Performance: The Complete Guide]]></title>
            <link>https://medium.com/@0x48core/promql-performance-the-complete-guide-88bb5f9b18cd?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/88bb5f9b18cd</guid>
            <category><![CDATA[high-performance]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[recording-rules]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 17:15:22 GMT</pubDate>
            <atom:updated>2026-03-11T17:15:22.884Z</atom:updated>
            <content:encoded><![CDATA[<p>Prometheus is powerful, but it’s also easy to write queries that quietly crush your infrastructure at scale. A dashboard that works fine with 10 services can start timing out when you have 500 — not because Prometheus is slow, but because the queries were never designed with performance in mind.<br>This guide walks through every major lever you have to speed up PromQL, from the fundamentals of how label matching works to the nuclear option of recording rules.</p><h3>1. Label Matcher Operators</h3><p>This is the single most impactful thing most engineers get wrong. Prometheus has four label matchers, and they are <em>not</em> equal in cost:</p><ul><li>= : exact match, fast, O(1) inverted-index lookup.</li><li>!= : exact negative, medium, index lookup + exclusion</li><li>= ~ : regex match, slow, scan all values, run regex per candidate</li><li>! ~ : regex negative, slowest, scan all values + exclude matches</li></ul><h4>Why exact match wins</h4><p>Prometheus maintains an inverted index per label: a map from each label value -&gt; list of matching time series. An = matcher hits this index in O(1) and immediately returns the series set.</p><p>A regex matcher =~ bypasses the index. It must enumerate every known value for that label name, compile and run the regex on each one, then resolve the posting lists for matches. Even for a simple literal like =~”prod” , Prometheus still takes the regex code path — it doesn’t automatically detect that prod is a plain string.</p><blockquote>Recent versions of Prometheus TSDB do optimize fully anchored literals like =~&quot;^prod$&quot; into an exact match. But this is not guaranteed across all versions, and unanchored patterns like =~&quot;prod&quot; are never optimized.</blockquote><h4>Practical example</h4><pre># slower<br>sum(metric{ env=~&quot;prod&quot;, service=~&quot;payments&quot;})<br><br># faster<br>sum(metric{ env=&quot;prod&quot;, service=&quot;payments&quot;})</pre><p>The only time you genuinely need =~ is for multi-value Grafana variables (<em>All</em> section) or real pattern matching. If your template variable always resolves to a single value, switch to =.</p><h3>2. Use the Smallest Viable Time Range</h3><p>The range duration in a range vector — [5m], [1h] — directly controls how many data points Prometheus loads from disk per series. Larger windows mean more I/O, more memory, more CPU. Always use the minimum windows that gives you a mathematically.</p><h4>Rate Window: How Small Can You Go?</h4><p>For rate(), the window should be at least 4 x the scrape interval to ensure at least 4 samples for a stable calculation. With a 15s scrape interval, that means [1m] is your floor — not [5m].</p><pre># Unnecessary wide<br>rate(http_requests_total[1h])<br><br># Appropriate window<br>rate(http_requests_total[5m])</pre><blockquote>In Grafana, use $__rate_interval instead of a hardcoded window. It automatically adapts to the dashboard&#39;s resolution and scrape interval, avoiding both over-sampling and under-sampling.</blockquote><h4>Query Time Range vs Range Vector</h4><p>These are two different things:</p><ul><li><strong>Query time range </strong>— the “Last 6h” selector in Grafana. Controls how many steps are evaluated.</li><li><strong>Range vector window</strong> — the [5m] in rate(…[5m]). Controls how many raw samples are loaded per step.</li></ul><p>Both contribute to query cost. Keep both as right as your use case allows.</p><h3>3. Filter Before Aggregating</h3><p>This is a cardinality problem. If you aggregate first and filter second, Prometheus loads all matching time series into memory to build the aggregation, then discards the rows you didn’t want. If you filter at the selector level, those series are never loaded at all.</p><pre># ❌ filter after aggregate<br>sum(metric) by (service) != 0 # Loads All Services first<br><br># ✅ filter at selector<br>sum(metric{service = &quot;payments&quot;})</pre><h4>Drop Labels You Don’t Need</h4><p>Every unique combination of label values is a separate time series. A high-cardinality label in your by() clause multiples the series count and memory usage for the aggregation. Be explicit about which dimensions you actually need.</p><pre># Bad: keeps all labels in output → high cardinality result<br>sum(http_requests_total)<br><br># Good: only keep what the dashboard widget needs<br>sum(http_requests_total) by (service, status_code)</pre><h3>4. Recording Rules — The Nuclear Option</h3><p>Recording rules are the most powerful performance tool in Prometheus. Instead of re-evaluating an expensive query on every dashboard refresh, Prometheus evaluates it on a schedule (e.g. every minute) and stores the result as a new metric. Your dashboard then queries that lightweight metric instead.</p><p>Think of it like a <strong>materialized view</strong> in a database — the expensive computation happens once, asynchronously, and you just read the cache.</p><pre># prometheus/rules/recording_rules.yml<br>groups:<br>  - name: http_perf<br>    interval: 1m          # re-evaluate every minute<br>    rules:<br>      - record: job:http_requests:rate5m<br>        expr: |<br>          sum(rate(http_requests_total[5m]))<br>            by (job, status_code)<br><br>      - record: job:http_errors:ratio5m<br>        expr: |<br>          sum(rate(http_requests_total{status_code=~&quot;5..&quot;}[5m])) by (job)<br>          /<br>          sum(rate(http_requests_total[5m])) by (job)</pre><p>Your dashboard query becomes trivially cheap:</p><pre># Before: expensive, runs on every panel refresh for every user<br>sum(rate(http_requests_total[5m])) by (job, status_code)<br><br># After: instant lookup, pre-computed every minute<br>job:http_requests:rate5m</pre><blockquote>Naming convention matters. Use the format level:metric:operations (e.g., job:http_requests:rate5m). This is the Prometheus community standard and makes recorded metrics self-documenting.</blockquote><h4>When to use recording rules</h4><ul><li>Any query used in a dashboard that many users open simultaneously.</li><li>Queries involving multi-level aggregations, joins, or long range windows.</li><li>Alert rules that involve expensive computations (alerts fire faster when pre-recorded).</li></ul><h3>5. Avoid Joins on High-Cardinality Labels</h3><p>Binary operations like * on(...) group_left(...) require Prometheus to build hash maps in memory — one entry per unique label combination. On high-cardinality labels, this can easily consume gigabytes of RAM and take seconds to resolve.</p><pre># Dangerous if &quot;pod&quot; or &quot;namespace&quot; have thousands of values<br>metric_a * on(pod, namespace) group_left(owner) metric_b</pre><h4>Mitigation strategies</h4><ol><li><strong>Reduce join key cardinality</strong> — aggregate to a coarser level before joining (e.g., join on job instead of pod).</li><li><strong>Pre-record one side </strong>— if one of the metrics being joined is itself expensive to compute, record it first and join against the recording.</li><li><strong>Add labels at scrape time</strong> — use relabeling rules to attach static metadata to series, eliminating the need for a runtime join entirely.</li></ol><pre># prometheus.yml — attach &quot;team&quot; label at scrape time<br>relabel_configs:<br>  - source_labels: [__meta_kubernetes_pod_label_team]<br>    target_label: team</pre><h3>6. Aggregation Order Matters</h3><p>In nested aggregations, the order of operations affects how much data flows through each layer. The goal is to reduce data volume as early as possible — the outer aggregation should receive the smallest possible input set.</p><pre>❌ Wasteful<br># Full-resolution inner query<br># fed into outer aggregation<br>sum(sum_over_time(<br>  metric[1h]<br>))<br><br>✅ Efficient<br># Pre-aggregate with recording rule,<br># outer sum is trivial<br>sum(job:metric:sum1h)</pre><p>The same principle applies to by() clauses in chained sum(sum(...)) patterns — reduce cardinality at the innermost layer.</p><h3>7. Subqueries: Convenient but Expensive</h3><p>Subqueries ([range:step]) let you apply range functions over instant vectors. They look elegant, but they silently evaluate the inner query at every step of the resolution, which can multiply query cost by 10-60×.</p><pre># This looks simple but runs rate() 60 times (1h/1m steps)<br>max_over_time(rate(http_requests_total[5m])[1h:1m])</pre><blockquote>A subquery with [1h:1m] means the inner expression is evaluated 60 times. On a metric with 1,000 time series, that&#39;s 60,000 evaluations per dashboard refresh. This is a very easy way to overload a Prometheus instance.</blockquote><h4>The right fix</h4><p>Record the inner expression with a recording rule, then apply the outer function directly against the recording. The recording is already pre-computed at the desired resolution:</p><pre># Recording rule (runs once per minute)<br>- record: job:http_requests:rate5m<br>  expr: rate(http_requests_total[5m])<br><br># Dashboard query (now trivially fast)<br>max_over_time(job:http_requests:rate5m[1h])</pre><h3>8. Grafana-Specific Optimizations</h3><p>Grafana adds its own layer of performance concerns on top of raw PromQL. Here are the Grafana settings that have the biggest impact:</p><ul><li><strong>Min interval</strong>: Set to your scrape interval (e.g. 15s) =&gt; Prevents Grafana from requesting sub-scrape-interval steps, which returns duplicate data and wastes CPU</li><li><strong>Max data points</strong>: Cap at 500–1000 per panel =&gt; Reduces the number of query steps; fewer steps = fewer evaluations</li><li><strong>$__rate_interval: </strong>Use instead of hardcoded [5m] =&gt; Dynamically adapts to dashboard resolution and scrape interval.</li><li><strong>Multi-value variables:</strong> Switch to = when single value is selected =&gt; Avoids unnecessary regex overhead on the most common case</li><li><strong>Query caching:</strong> Enable Grafana query caching (Grafana 9+) =&gt; Identical queries from different users hit the cache rather than Prometheus</li></ul><blockquote>For multi-value template variables: when exactly one value is selected, Grafana’s =~&quot;value&quot; pattern can be replaced with =&quot;value&quot; using a conditional variable expression. This is worth doing for high-traffic dashboards.</blockquote><h3>Priority Order: Where to Start</h3><ol><li><strong>Recording Rules: </strong>10–100× speedup on dashboards. Pre-compute once, query unlimited times.</li><li><strong>Exact Matchers: </strong>Replace =~ with = wherever the value is known. Free performance.</li><li><strong>Filter Early: </strong>Move label filters into selectors. Reduce cardinality before aggregation.</li><li><strong>Shrink Windows: </strong>Use the minimum viable range vector. Use $__rate_interval in Grafana.</li><li><strong>Eliminate Subqueries: </strong>Replace [range:step] subqueries with recording rules where possible.</li></ol><h3>Wrapping Up</h3><p>PromQL performance is rarely about a single silver bullet — it’s a layered discipline. Start with the high-impact changes (recording rules, exact matchers) and work your way down as your scale demands. Most teams find that recording rules for their top 10 most-queried metrics alone eliminates 80% of their Prometheus CPU load.</p><p>The best query is one that never runs at all — pre-computed, cached, and ready to serve at microsecond latency. That’s the goal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88bb5f9b18cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your POST /orders Should Return 202, Not 200]]></title>
            <link>https://medium.com/@0x48core/why-your-post-orders-should-return-202-not-200-a566f4e8a8e5?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/a566f4e8a8e5</guid>
            <category><![CDATA[api-design]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 18:46:27 GMT</pubDate>
            <atom:updated>2026-03-10T18:46:27.009Z</atom:updated>
            <content:encoded><![CDATA[<p>When a user clicks “Place Order,” your backend has to talk to a payment gateway, a fraud checker, an inventory system, and a fulfillment service. Some of those calls take seconds. Some fail randomly.</p><p>The naive fix is to do everything inline and return 200 OK when it&#39;s all done. That&#39;s a mistake.</p><h3>The Problem</h3><p>Chaining all downstream calls synchronously means:</p><ul><li><strong>Latency adds up</strong> — 4 services × 2s each = 8s user wait time</li><li><strong>One failure = full failure</strong> — your endpoint’s availability is the <em>product</em> of all services</li><li><strong>Retry = double charge</strong> — no idempotency means a network hiccup bills the user twice</li></ul><h3>The Right Approach: Accept Now, Process Later</h3><pre>POST /orders<br>→ 202 Accepted  (in ~50ms)<br>   Location: /orders/abc123/status</pre><p>You accept the request immediately, persist it, and push work onto a <strong>durable message queue</strong>. Background consumers handle the slow stuff.</p><pre>GET /orders/abc123/status</pre><pre>{<br>  &quot;status&quot;: &quot;confirmed&quot;,<br>  &quot;steps&quot;: {<br>    &quot;fraud_check&quot;: &quot;passed&quot;,<br>    &quot;payment&quot;:     &quot;charged&quot;,<br>    &quot;inventory&quot;:   &quot;reserved&quot;,<br>    &quot;fulfillment&quot;: &quot;dispatched&quot;<br>  }<br>}</pre><h3>Three Properties That Make It Work</h3><p><strong>Durability</strong> — the message queue buffers failures. If fulfillment goes down for 10 minutes, orders queue up and drain when it recovers.</p><p><strong>Idempotency</strong> — clients send an idempotency_key. Duplicate requests return the cached result, no side effects.</p><p><strong>Observability</strong> — every message carries a trace_id across all services. When an order gets stuck, you know exactly where and why.</p><h3>Tradeoffs</h3><p>The async approach costs more to build. That complexity is the honest price of the guarantees you get.</p><blockquote><em>A slow third-party service shouldn’t be your users’ problem. It should be your on-call engineer’s alert.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a566f4e8a8e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleflight in Go: How One Line of Code Saved Our Database from a Cache Stampede]]></title>
            <link>https://medium.com/@0x48core/singleflight-in-go-how-one-line-of-code-saved-our-database-from-a-cache-stampede-c969d20f8133?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/c969d20f8133</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[singleflight]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 17:44:59 GMT</pubDate>
            <atom:updated>2026-03-01T17:44:59.151Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>A practical guide to </em><em>golang.org/x/sync/singleflight with a fully working demo, Prometheus metrics, and Grafana dashboards.</em></blockquote><p>It was 2 AM when the alert fired. Our template service — a straightforward Go microservice running on Kubernetes — had been humming along for months. Redis sat in front of PostgreSQL, caching template data with a 30-second TTL. Response times were consistently under 5ms. Life was good.</p><p>Then a transient network blip severed the connection between our pod and the Redis cluster. Suddenly, every single request became a cache miss. Two hundred concurrent users, each asking for the same template, each firing their own query straight to PostgreSQL. The database connection pool saturated in seconds. Queries started timing out. The service went down. And so did everything that depended on it.</p><p>This is a <strong>cache stampede</strong>, and it’s one of the most common failure modes in read-heavy distributed systems. In this article, I’ll show you how Go’s singleflight package can prevent it — and I’ll walk through a complete, production-style demo you can run yourself.</p><h3>What Is a Cache Stampede?</h3><p>A cache stampede (sometimes called a “thundering herd”) happens when a cached value expires or becomes unavailable, and many concurrent requests race to regenerate it. Instead of one request fetching from the database and populating the cache, <em>every</em> request independently hits the backend.</p><pre>Cache Miss!<br>[ PostgreSQL drowning in identical queries ]</pre><p>The math is brutal. If you serve 200 requests per second for a key with a 30-second TTL, every time that key expires you get up to 200 simultaneous database queries — all returning the exact same data.</p><h3>The Fix: singleflight</h3><p>Go’s golang.org/x/sync/singleflight package provides a deceptively simple solution. It ensures that for any given key, only <strong>one</strong> function execution is in-flight at a time. All other callers for the same key block and receive the same result once the single execution completes.</p><p>The API surface is tiny:</p><pre>var group singleflight.Group<br>result, err, shared := group.Do(&quot;my-key&quot;, func() (interface{}, error) {<br>  // Only ONE goroutine executes this, even if 200 call Do() concurrently<br>  return fetchFromDatabase(&quot;my-key&quot;)<br>})<br>// shared == true means this caller reused another caller&#39;s result</pre><p>That’s it. One line wrapping your expensive operation, and you’ve eliminated redundant work.</p><h3>Building a Real Demo</h3><p>Theory is nice, but let’s see it work. I built a complete service that demonstrates the pattern end-to-end: a Go HTTP API backed by PostgreSQL and Redis, with Prometheus metrics and a Grafana dashboard to visualize the deduplication in real time.</p><h4>Architecture</h4><pre>Client Request<br>|<br>v<br>[HTTP Handler] → Prometheus metrics: request count, latency, in-flight<br>|<br>v<br>[TemplateService]<br>|<br>+ → [Redis Cache] - HIT → return cached value<br>|<br>+ → [singleflight.Group.Do(key)] - deduplicates concurrent calls<br>|<br>v<br>[PostgreSQL] → fetch from DB, populate cache (TTL 30s)</pre><p>The flow is classic <strong>cache-aside</strong>:</p><p>1. Check Redis. If the value exists, return it immediately.</p><p>2. On a cache miss, use `singleflight` to ensure only one goroutine queries PostgreSQL.</p><p>3. The winner writes the result back to Redis with a 30-second TTL.</p><p>4. All concurrent callers receive the same result.</p><h4>The Core Code</h4><p>Here’s the TemplateService — the heart of the pattern:</p><pre>type TemplateService struct {<br>  cache Cache<br>  repo Repository<br>  group singleflight.Group<br>}<br>func (s *TemplateService) GetTemplate(ctx context.Context, id string) (string, error) {<br>  key := fmt.Sprintf(&quot;template:%s&quot;, id)<br>  // Step 1: Try the cache<br>  val, err := s.cache.Get(ctx, key)<br>  if err != nil &amp;&amp; !errors.Is(err, redis.Nil) {<br>    return &quot;&quot;, fmt.Errorf(&quot;failed to get template from cache: %w&quot;, err)<br>  }<br>  if err == nil {<br>    metrics.CacheHits.Inc()<br>    return val, nil<br>  }<br>  // Step 2: Cache miss - use singleflight to deduplicate DB calls<br>  metrics.CacheMisses.Inc()<br>  result, err, shared := s.group.Do(key, func() (interface{}, error) {<br>  metrics.DBHits.Inc()<br>  ctx, cancel := context.WithTimeout(ctx, 2*time.Second)<br>  defer cancel()<br>  val, err := s.repo.GetByID(ctx, id)<br>  if err != nil {<br>    return &quot;&quot;, fmt.Errorf(&quot;failed to get template from database: %w&quot;, err)<br>  }<br>  // Step 3: Populate the cache<br>  _ = s.cache.Set(ctx, key, val, 30*time.Second)<br>    return val, nil<br>  })<br>  if shared {<br>    metrics.SingleflightShared.Inc()<br>  }<br>  if err != nil {<br>    return &quot;&quot;, fmt.Errorf(&quot;failed to get template: %w&quot;, err)<br>  }<br>  return result.(string), nil<br>}</pre><p>A few things worth noting:</p><p>- <strong>The singleflight key matches the cache key</strong> (template:&lt;id&gt;), so deduplication is scoped per template.</p><p>- <strong>shared tells you whether the result was reused.</strong> We track this as a Prometheus counter so we can see exactly how much work was saved.</p><p>- <strong>A 2-second timeout</strong> is applied inside the callback to prevent a slow DB query from holding up all waiting goroutines indefinitely.</p><h4>Observability</h4><p>You can’t improve what you can’t measure. The service exports seven Prometheus metrics:</p><pre>| Metric | Type | What It Tells You |<br>| - - - - | - - - | - - - - - - - - - -|<br>| `http_request_total` | Counter | Request volume by path, method, and status code |<br>| `http_request_duration_seconds` | Histogram | Latency distribution (P50, P95, P99) |<br>| `cache_hits_total` | Counter | Requests served from Redis |<br>| `cache_misses_total` | Counter | Requests that fell through to singleflight |<br>| `db_hits_total` | Counter | Actual PostgreSQL queries executed |<br>| `singleflight_shared_total` | Counter | Results shared across concurrent callers |<br>| `http_in_flight_requests` | Gauge | Current concurrency |</pre><p>These metrics tell a clear story. In a healthy system, `cache_hits_total` should dominate. `db_hits_total` should be a small fraction. And `singleflight_shared_total` tells you exactly how many redundant queries were prevented.</p><h3>Running the Demo</h3><p>The entire stack is containerized. One command gets you everything:</p><pre>docker compose up - build -d</pre><p>This starts five services:</p><pre>| Service | Port | Purpose |<br>| - - - - -| - - - | - - - - -|<br>| **app** | 8080 | Go singleflight service |<br>| **postgres** | 5432 | PostgreSQL with seeded template data |<br>| **redis** | 6379 | Cache layer |<br>| **prometheus** | 9090 | Metrics scraping every 5 seconds |<br>| **grafana** | 3000 | Pre-configured dashboard (admin/admin) |</pre><p>Test with a single request:</p><pre>curl &quot;http://localhost:8080/template-details?id=1&quot;</pre><p>Then hammer it with the included load test:</p><pre>./loadtest.sh</pre><p>The load test fires 25 waves of 200 concurrent requests, each wave targeting a random template ID. This maximizes the chance of concurrent calls for the same key — exactly the scenario singleflight is designed for.</p><h3>Results: 97% Reduction in Database Load</h3><p>After running the load test (~7,500 total requests), here’s what the metrics show:</p><pre>| Metric | Value | Meaning |<br>| - - - - | - - - -| - - - - -|<br>| Total requests | ~7,500 | Including spread requests between waves |<br>| Cache hit rate | **~97%** | The vast majority served from Redis |<br>| DB queries | **~220** | Only ~3% of requests actually hit PostgreSQL |<br>| Singleflight shared | **~18** | Concurrent duplicate calls that were deduplicated |</pre><p>Without singleflight, every cache miss under concurrent load would have generated a separate database query. With it, 200 concurrent requests for the same expired key produce <strong>one</strong> database call instead of 200.</p><p>Open Grafana at http://localhost:3000, navigate to the <strong>Singleflight Service Dashboard</strong>, and set the time range to <strong>Last 5 minutes</strong>. You’ll see the cache hit rate climbing, database hits staying flat, and singleflight shared calls spiking during burst traffic.</p><h3>Wrapping Up</h3><p>Cache stampedes are a real and common problem in production systems. Go’s singleflight package provides an elegant, zero-dependency (well, one import) solution that can be added to existing cache-aside patterns with minimal code changes.</p><p>The key takeaway: <strong>if multiple goroutines are asking for the same thing at the same time, only one of them should do the actual work. </strong>That’s singleflight in a sentence.</p><p>The full source code — including Docker Compose, Prometheus, Grafana dashboards, and load test scripts — is available on GitHub: <a href="https://github.com/augustus281/go-latency"><strong>github.com/augustus281/go-latency</strong></a></p><p><em>If you found this useful, feel free to give the repo a star and share it with your team. Got questions or war stories about cache stampedes? Drop a comment below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c969d20f8133" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Transactions Are Your Database’s Superpower (And When They Fail You)]]></title>
            <link>https://medium.com/@0x48core/transaction-d9e83ccca197?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9e83ccca197</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[acid]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 10:28:19 GMT</pubDate>
            <atom:updated>2026-01-25T10:32:10.581Z</atom:updated>
            <content:encoded><![CDATA[<p>Data systems operate in a failure-prone world: crashes, network drops, concurrent writes, partial updates, and race conditions are inevitable. Left unchecked, these issues quickly lead to corrupted or inconsistent data.</p><p>Transactions were created to handle this chaos. They bundle multiple reads and writes into a single all-or-nothing operation, eliminating partial failures and simplifying application logic by pushing complexity into the database.</p><p>But transactions aren’t free — or always necessary. Some systems relax guarantees to gain performance or availability. To make the right trade-off, you need to understand what transactions really guarantee, what they cost, and how isolation levels like read committed, snapshot isolation, and serializability work under the hood.</p><h3>The Slippery Concept of a Transaction</h3><p>Most relational databases still rely on the transaction model introduced by IBM System R in 1975, and modern systems like MySQL and PostgreSQL remain remarkably similar to it. In contrast, the rise of NoSQL databases in the late 2000s often came at the cost of abandoning or weakening transactional guarantees in favor of new data models, replication, and partitioning.</p><p>This shift led to polarized views: some claimed transactions prevent scalability, while others treated them as mandatory for serious applications. Both extremes are misleading. Transactions, like any design choice, involve trade-offs, and understanding their guarantees and limitations is essential to using them effectively in real-world systems.</p><h4>The Meaning of ACID</h4><p>If you’ve worked with databases, you’ve almost certainly heard of <strong>ACID</strong> — the famous acronym for <strong>Atomicity, Consistency, Isolation, and Durability</strong>. Coined in 1983, ACID was meant to give engineers a precise way to talk about transaction safety and fault tolerance in databases.</p><p>On paper, it sounds solid. In practice, it’s messy.</p><p>The problem is that <strong>ACID doesn’t mean the same thing everywhere</strong>. Different databases implement these guarantees differently, and nowhere is this more confusing than with <em>isolation</em>. Two systems can both claim to be “ACID-compliant” while providing very different real-world behaviors.</p><p>As a result, ACID has slowly drifted from a strict technical definition into something closer to a <strong>marketing label</strong>. When a database advertises ACID compliance today, it’s often unclear what guarantees you’re actually getting.</p><p>You’ll sometimes hear the alternative term <strong>BASE</strong> — <em>Basically Available, Soft state, Eventual consistency</em> — used to describe non-ACID systems. Unfortunately, BASE is even vaguer. In many cases, it simply means “not ACID,” which isn’t particularly helpful.</p><p>To truly understand transactions, we need to move past the buzzwords. The only way forward is to examine what <strong>atomicity, consistency, isolation, and durability</strong> actually guarantee — and where those guarantees break down in real systems.</p><h4>Atomicity: All or Nothing, or Nothing at All</h4><p>In computer science, <em>atomic</em> generally means “indivisible.” But the exact meaning depends on context.</p><p>In multithreaded programming, an atomic operation guarantees that no other thread can observe a half-finished state. The system is either in the state before the operation or after it — never somewhere in between.</p><p><strong>ACID atomicity means something different.</strong><br> It is not about concurrency. It does not describe what happens when multiple clients access the same data at the same time. That responsibility belongs to <strong>isolation</strong>.</p><p>Instead, ACID atomicity answers a simpler — and more dangerous — question:</p><blockquote><em>What happens when something goes wrong halfway through a transaction?</em></blockquote><p>A transaction often consists of multiple write operations. During execution, the process may crash, the network may fail, disk space may run out, or a constraint may be violated. Without atomicity, the database can be left in an undefined state: some writes applied, others lost.</p><p>That ambiguity is toxic.</p><p>Atomicity eliminates it by enforcing a single rule: <strong>all or nothing</strong>.<br> If a transaction cannot be committed, it is aborted, and <strong>every write performed as part of that transaction is rolled back</strong>.</p><p>This property enables one of the most important behaviors in reliable systems: <strong>safe retries</strong>. When a transaction fails, the application can retry without worrying about duplicated writes or corrupted state.</p><p>At its core, atomicity is about <strong>abortability</strong> — the guarantee that partial work never leaks into the system. The name may be imperfect, but the promise is not.</p><h4>Consistency: The Most Misunderstood Letter in ACID</h4><p>It’s unfortunate that the same word — <em>consistency</em> — is used to mean at least four different things in distributed systems. Nowhere is this more confusing than in <strong>ACID</strong>.</p><p>Even one of the field’s most respected voices, Joe Hellerstein, has joked that the <strong>“C” in ACID was added just to make the acronym work</strong>. And honestly, that tells you a lot.</p><p>In the ACID model, consistency does <em>not</em> mean high availability, replication correctness, or agreement across nodes. Instead, it refers to <strong>application-defined invariants</strong> — rules that must always hold true for your data.</p><p>In an accounting system, for example, total credits and debits must always balance. If a transaction starts from a valid state and all its writes preserve that rule, the system remains consistent.</p><p>Here’s the catch: <strong>the database doesn’t know your invariants</strong>.</p><p>The responsibility for maintaining consistency lies primarily with the <strong>application</strong>, not the database. If your application writes data that violates its own business rules, the database will happily store it. A database can enforce certain structural constraints — foreign keys, uniqueness, non-null fields — but it cannot understand your domain logic.</p><p>This leads to an uncomfortable truth: <strong>atomicity, isolation, and durability are database guarantees, but consistency isn’t</strong>. Applications rely on the database’s atomicity and isolation to <em>help</em> maintain consistency, but the final responsibility still sits in application code.</p><p>Which is why the “C” in ACID often causes more confusion than clarity. It sounds like a database guarantee, but in practice, it’s a contract between your application logic and the transactions you design.</p><h4>Isolation: When Transactions Stop Stepping on Each Other</h4><p>Most databases are used by many clients at the same time. That’s perfectly fine — as long as those clients aren’t touching the same data.<br>The trouble starts when they are.</p><p>Consider a simple example: two clients incrementing the same counter stored in a database. Each client reads the current value, adds one, and writes it back. If the counter starts at 42, you’d expect it to end up at 44.</p><p>Instead, it ends up at <strong>43</strong>.</p><p>Why? A classic <strong>race condition</strong>. Both clients read the value 42 before either writes back, and one update overwrites the other. One increment is effectively lost.</p><p>This is exactly the class of problems that <strong>isolation</strong> in ACID is meant to prevent.</p><p>In the ACID sense, isolation means that <strong>concurrently executing transactions are shielded from one another</strong>. They shouldn’t see each other’s intermediate state, and they shouldn’t interfere in ways that produce incorrect results.</p><p>Traditional database theory defines isolation using a very strong concept called <strong>serializability</strong>. Under serializable isolation, each transaction can behave <em>as if it were the only transaction running on the entire database</em>. Even if transactions actually run in parallel, the final outcome must be the same as if they had run one after another.</p><p>It’s a powerful guarantee — and an expensive one.</p><p>In practice, fully serializable isolation is rarely used because it comes with a significant performance cost. Some widely used databases don’t even implement it. For example, Oracle offers an isolation level called “serializable,” but under the hood it actually provides <strong>snapshot isolation</strong>, which is weaker than true serializability.</p><p>These weaker isolation levels trade correctness guarantees for performance and scalability. They prevent some race conditions, but not all. Understanding where they fall short is critical — and that’s where things get interesting.</p><h4>Durability: The Promise That Data Won’t Be Forgotten</h4><p>At its core, a database exists for one reason: <strong>to keep data safe</strong>.<br> Durability is the promise that once a transaction successfully commits, its data will survive — even if the database crashes or hardware fails.</p><p>In a single-node database, durability usually means that data has been written to <strong>non-volatile storage</strong> such as a hard drive or SSD. This is typically backed by a <strong>write-ahead log (WAL)</strong> or a similar mechanism, which allows the database to recover if on-disk data structures become corrupted.</p><p>In replicated systems, durability often means something slightly different: the transaction is only considered committed once the data has been <strong>successfully copied to a certain number of replicas</strong>. To uphold this guarantee, the database must wait for those writes or replications to complete before reporting success to the client.</p><p>Of course, it’s important to acknowledge an uncomfortable truth: <strong>perfect durability does not exist</strong>. If all disks, replicas, and backups are destroyed at the same time, no database can save you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9e83ccca197" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service Discovery with Kubernetes]]></title>
            <link>https://medium.com/@0x48core/service-discovery-with-kubernetes-dd99f7fdb275?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd99f7fdb275</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[service-discovery]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 18:00:34 GMT</pubDate>
            <atom:updated>2025-12-13T18:01:27.150Z</atom:updated>
            <content:encoded><![CDATA[<p>The Service Discovery pattern provides a stable endpoint at which clients of a service can access the instances providing the service. For this purpose, Kubernetes provides multiple mechanisms, depending on whether the service consumers and producers are located on or off the cluster.</p><h3>Problem</h3><p>Applications running on Kubernetes rarely operate in isolation and often need to communicate with other services inside or outside the cluster. While some workloads actively initiate outgoing connections, many long-running services depend on incoming requests from dynamic and elastically scaled Pods. Because Pod IPs change frequently and replicas scale up and down, manually tracking service endpoints would be complex and error-prone. To address this challenge, Kubernetes provides built-in service discovery mechanisms that enable reliable communication between services.</p><h3>Solution</h3><h4>1. Internal Service Discovery</h4><p>When applications run with multiple Pods in Kubernetes, Pod IPs are dynamic and cannot be relied on for direct communication. Kubernetes Service solve this by providing a stable virtual IP and DNS name that routes traffic to matching Pods using label selectors. Client interacts with the Service endpoint, while Kubernetes handles Pod discovery and load balancing automatically.</p><h4>1.1. Discovery through environment variables</h4><p>When a Kubernetes Service is created, it is assigned a stable virtual IP address called a <strong>ClusterIP</strong>, which is accessible only from within the cluster and remains unchanged for the lifetime of the Service. To allow Pods to discover this dynamically allocated IP, Kubernetes provides a service discovery mechanism based on environment variables. As Pod startup time, Kubernetes injects environment variables containing the host and port information of all existing Services into the Pod. Applications can be implemented to read these variables using the known Service name, making this approach language-agnostic and easy to use, even in local development environments.</p><p>However, this mechanism has an important limitation: environment variables are only populated when the Pod starts. If a Service is created<br>after a Pod is already running, the Pod will not receive the corresponding Service environment variables. As a result, this approach introduces a <br>temporal dependency between Service creation and Pod startup, often requiring Services to be defined before dependent Pods or Pods to be restarted. Due to this limitation, environment-variable-based discovery is typically suitable for simple or static setups.</p><h4>1.2. Discovery through DNS lookup</h4><p>Kubernetes provides DNS-based Service Discovery through an internal DNS server that all Pods use by default. Each Service automatically receives a DNS entry, allowing Pods to access it via a stable name instead of dynamic IP address. This mechanism works immediately for all Pods, regardless of when they were started, unlike environment-variable-based discovery. DNS discovery is the recommended and most flexible approach for service-to-service communication in Kubernetes.</p><p><strong>ClusterIP</strong> is the default Kubernetes Service type that provides a stable virtual IP for accessing a group of Pods inside the cluster. It supports multiple ports, simple L4 load balancing, optional session affinity based on client IP, and integrates with readiness probes to route traffic only the healthy Pods. The ClusterIP is a virtual address implemented via kube-proxy and iptables, not a real network interface, and is accessible only within the cluster. ClusterIP is the most commonly used Service type for internal service discovery and communication between microservices.</p><h4>2. Manual Service Discovery</h4><p>Kubernetes Services typically use selectors to automatically route traffic to ready Pods via dynamically managed Endpoints. However, a Service can also be created without a selector, allowing Endpoints to be defined manually and point to external IP addresses or custom backends. This approach enables clients to access both internal and external through a stable ClusterIP and standard Service discovery mechanisms (DNS or environment variables). It is especially useful for migrating services <br>without changing client configurations.</p><h4>3. Service Discovery from Outside the Cluster</h4><p>While ClusterIP Services are only accessible in the Kubernetes cluster, external clients often need to access service running in Pods. A Service of type <strong>NodePort</strong> exposes an application outside the cluster by reserving a port every node and forwarding traffic to the Service’s ClusterIP and then to the Pods. This allows external clients to reach the service using <strong>&lt;NodeIP&gt;:&lt;NodePort&gt;</strong>. NodePort is simple to use but exposes the service on all nodes and is typically a building block for more advanced exposure methods.</p><ul><li><strong>Port Number:</strong> Instead of picking a specific port with nodePort: 30036, you can let Kubernetes pick a free port within its range.</li><li><strong>Firewall rules:</strong> Since this method opens a port on all the nodes, you may have to configure additional firewall rules to let external clients access the node ports.</li><li><strong>Node selection:</strong> An external client can open connection to any node in the cluster. However, if the node is not available, it is the responsibility of the client application to connect to another healthy node. For this purpose, it may be a good idea to put a load balancer in front of the nodes that picks healthy nodes and perform failover.</li><li><strong>Pods selection:</strong> NodePort allows external access to a Service, with traffic routed to a randomly selected Pod. Setting `externalTrafficPolicy:Local` ensures traffic only reaches Pods on the same node, but requires either a Pod on every node or that the client knows which nodes have healthy Pods.</li><li><strong>Source addresses: </strong>With a <strong>NodePort Service</strong>, client source IPs are <strong>NATed</strong>, so Pod see the node’s IP instead of the real client IP. Setting externalTrafficPolicy: Local preserves the client IP by routing traffic only to Pods on the same node.</li></ul><h4>Reference:</h4><ul><li><a href="https://github.com/augustus281/k8s-hands-on">https://github.com/augustus281/k8s-hands-on</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd99f7fdb275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prepared Statement]]></title>
            <link>https://medium.com/@0x48core/prepared-statement-089f97cb8a75?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/089f97cb8a75</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[pgx]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 16:38:25 GMT</pubDate>
            <atom:updated>2025-09-18T16:38:25.688Z</atom:updated>
            <content:encoded><![CDATA[<p>Prepared Statement with Go/pgx!</p><h3>1. What is a prepared statement?</h3><p>In PostgreSQL (and many other databases), a prepared statement means:</p><ul><li>The database parses, plan, and optimizes the SQL query once.</li><li>After that, the statement can be reused multiple times with different parameters.</li></ul><p><strong>Example</strong>:</p><pre>-- prepared statement (parse + plan once)<br>PREPARE get_user (int) AS<br>SELECT name FROM users WHERE id = $1;</pre><pre>-- reused state multiple times<br>EXECUTE get_user(1);<br>EXECUTE get_user(2);</pre><p>In Go/pgx, when you code:</p><pre>row := pool.QueryRow(ctx, &quot;SELECT name FROM users WHERE id=$1&quot;, userID)</pre><p>pgx can automatically use the prepared statement mechanism for you (depending on the configuration).</p><h3>2. If not using prepared statement</h3><p>Each time you query:</p><ol><li>PostgreSQL receives the SQL in string form.</li><li>Parse the SQL string → into a syntax tree (AST).</li><li>Plan → the DB computes an execution plan (which index to use, which join strategy, etc).</li><li>Optimize</li><li>Execute with parameters.</li></ol><p>⇒ Step 2–4 consume CPU and time, especially when the query is repeated thousands of times per second.</p><h3>3. If using prepared statement</h3><p>The parse/plan step runs only once, when preparing the statement.</p><p>For subsequent executions, the database only needs to bind the parameters and execute the existing plan.</p><p>Lower CPU usage (less overhead from parse/plan).</p><p>Lower latency (queries return faster).</p><h3>4. Real-world example</h3><p>A case where a query runs repeatedly, for example in an API:</p><pre>SELECT name FROM users WHERE id=$1;</pre><ul><li>If not prepared, the DB has to parse + plan again for each request → overhead.</li><li>If prepared, the DB only needs to bind $1 = userID and execute immediately → more efficient.</li></ul><h3>5. Trade-off</h3><ul><li>Prepared statements consume memory for caching.</li><li>If a query runs one or twice, the benefit it negligible.</li><li>But for hot paths, where queries run many times per second, performance improves significantly.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=089f97cb8a75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reference in Rust]]></title>
            <link>https://medium.com/@0x48core/reference-in-rust-64c9de84edc5?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/64c9de84edc5</guid>
            <category><![CDATA[reference]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 16:10:08 GMT</pubDate>
            <atom:updated>2025-08-31T16:10:08.833Z</atom:updated>
            <content:encoded><![CDATA[<p>The heart of Rust!</p><h4>1. What is References?</h4><p>Instead of moving the ownership of a value to another variable or function, Rust allows you to <em>borrow</em> that value using a <strong>reference</strong>.</p><ul><li>A reference is a “view” to data, not real data.</li><li>It is wrote by &amp;.</li><li>When pass reference in function, root value doesn’t lose ownership -&gt; after function run completely, you still use the initial value.</li></ul><pre>func do_stuff(s: &amp;String) {<br>  println!(&quot;Got: {}&quot;, s);<br>}<br><br>func main() {<br>  let s1 = String::from(&quot;hello&quot;);<br>  do_stuff(&amp;s1); // pass reference, s1 isn&#39;t moved.<br>  println!(&quot;{}&quot;, s1);  // still used<br>}</pre><h4>2. How References Work “Under The Hood”?</h4><p>When you create a reference like &amp;s1 , Rust actually creates a pointer to the underlying data.</p><p>However, unlike C/C++, Rust doesn’t require you to manually deal with raw pointers because:</p><ul><li>References are always valid thanks to the <strong>lifetime system</strong>.</li><li>There are no full references.</li><li>The compiler ensures you cannot have a reference that outlives the original data.</li></ul><h4>3. Immutable vs Mutable reference</h4><ul><li>By default, a reference is immutable: you cannot change the value through that reference.</li><li>If you want to modify the value, you need to use a <strong>mutable reference</strong>: &amp;mut.</li></ul><pre>fn change(s: &amp;mut String) {<br>    s.push_str(&quot; world&quot;); // can change because of &amp;mut<br>}<br><br>fn main() {<br>    let mut s = String::from(&quot;hello&quot;);<br>    change(&amp;mut s);<br>    println!(&quot;{}&quot;, s); // hello world<br>}</pre><h4>4. Dereference</h4><ul><li>A reference is similar to a pointer, so if you want to access the actual value, you need to <strong>deference</strong> it using *.</li><li>However, when you use the <strong>dot syntax</strong> (like s.len() or s.push_str()), Rust will automatically deference for you.</li></ul><h4>5. The Borrowing Rules (Reference Safety Rules)</h4><p>Rust enforces an important rule to prevent race conditions and data corruption:</p><p>At any given time, you can have either:</p><ul><li><strong>multiple immutable references (</strong><strong>&amp;T) or</strong></li><li><strong>exactly one mutable reference (</strong><strong>&amp;mut T)</strong></li></ul><p>You can’t have both at the same time!</p><pre>fn main() {<br>    let mut s = String::from(&quot;hello&quot;);<br>    let r1 = &amp;s;<br>    let r2 = &amp;mut s; // error: can&#39;t borrow mutable when having immutable<br>}</pre><h4>6. References and Threads (Borrowing Rules in Multithreading)</h4><p>These rules also apply in a multithreaded context:</p><ul><li>You can share multiple immutable references across many threads.</li><li>But a mutable reference can only be used by one thread at a time — unless you use synchronization mechanism such as <strong>locks, Mutex, RwLock,</strong> etc.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64c9de84edc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error Handling in Go Concurrency]]></title>
            <link>https://medium.com/@0x48core/error-handling-in-go-concurrency-f7215fee58e8?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7215fee58e8</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go-pattern]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 17:11:56 GMT</pubDate>
            <atom:updated>2025-08-24T17:12:47.634Z</atom:updated>
            <content:encoded><![CDATA[<p>Error handling is one of the most overlooked aspects of concurrent programming in Go. While we often focus on channels, goroutines, and synchronization, we sometimes forget to ask: <em>what happens when things go wrong?</em></p><h4>The Problem with Errors in Goroutines</h4><pre>checkStatus := func(<br> done &lt;-chan interface{},<br> urls ...string,<br>) &lt;-chan *http.Response {<br> responses := make(chan *http.Response)<br>   go func() {<br>     defer close(responses)<br>     for _, url := range urls {<br>       resp, err := http.Get(url)<br>       if err != nil {<br>       fmt.Println(err)continue<br>     }<br>     select {<br>     case &lt;-done:<br>     return<br>     case responses &lt;- resp:<br>     }<br>     }<br>  }()<br>     return responses<br>  }<br>  done := make(chan interface{})<br>  defer close(done)<br><br>  urls := []string{&quot;https://www.google.com&quot;, &quot;https://badhost&quot;}<br>  for response := range checkStatus(done, urls...) {<br>   fmt.Printf(&quot;Response: %v\n&quot;, response.Status)<br>  }</pre><p>Show the naive approach: goroutine just prints errors to stdout</p><p>Explain why this is a bad idea:</p><ul><li>Goroutine has no context to decide what to do.</li><li>Errors are lost or ignored.</li><li>Caller cannot react properly.</li></ul><h4>A Better Way: Coupling Results and Errors</h4><p>Introduce the idea of a Result struct:</p><pre>type Result struct {<br>    Error    error<br>    Response *http.Response<br>}</pre><p>Explain the philosophy:</p><ul><li>Goroutines should only <em>produce results</em> (which may include errors).</li><li>The parent goroutine (caller) should decide how to handle them.</li></ul><p>Show improved code where errors are sent through the same channel as results.</p><h4>Centralized Error Handling</h4><p>Show how the main goroutine can handle errors intelligently:</p><ul><li>Stop after too many errors.</li><li>Retry on transient errors.</li><li>Ignore certain errors.</li></ul><pre>errCount := 0<br>for result := range checkStatus(done, urls...) {<br>    if result.Error != nil {<br>        errCount++<br>        if errCount &gt;= 3 {<br>            fmt.Println(&quot;Too many errors, stopping...&quot;)<br>            break<br>        }<br>        continue<br>    }<br>    fmt.Println(&quot;Response:&quot;, result.Response.Status)<br>}</pre><h4>Why This Pattern Works</h4><ul><li>Separation of concerns: producer goroutines just <em>report</em>, consumer goroutines <em>decide</em>.</li><li>Consistency: mirrors Go’s synchronous error handling (if err != nil).</li><li>Flexibility: allows complex policies (retry, fallback, circuit breaker).</li></ul><h4>Conclusion</h4><p>By treating errors as first-class values in your concurrent programs, you gain the flexibility to build resilient systems that fail gracefully. Goroutines should not be left guessing what to do with errors — delegate that responsibility to the parent goroutine, where the full context of your program lives.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7215fee58e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The or-channel pattern in Go Concurrency]]></title>
            <link>https://medium.com/@0x48core/the-or-channel-pattern-in-go-concurrency-02d04a6b2706?source=rss-914a8bc5f029------2</link>
            <guid isPermaLink="false">https://medium.com/p/02d04a6b2706</guid>
            <category><![CDATA[go-pattern]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go-concurrency]]></category>
            <dc:creator><![CDATA[0x48core]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 09:55:04 GMT</pubDate>
            <atom:updated>2025-08-23T09:55:04.643Z</atom:updated>
            <content:encoded><![CDATA[<p>In Go, when working with multiple done channels (channels used to signal termination), you may sometimes want to combine them into a single channel that closes as soon as any of the underlying channels is closed.</p><p>In stead of writing a manual select statement, you can use <strong>or-channel pattern</strong> — a technique that leverages recursion and goroutines to merge multiple channels into one.</p><p><strong>Example</strong>:</p><pre>var or func(channels ...&lt;-chan interface{}) &lt;-chan interface{}<br>or = func(channels ...&lt;-chan interface{}) &lt;-chan interface{} {<br>    switch len(channels) {<br>    case 0:<br>        return nil<br>    case 1:<br>        return channels[0]<br>    }<br><br>    orDone := make(chan interface{})<br>    go func() {<br>        defer close(orDone)<br>        switch len(channels) {<br>        case 2:<br>            select {<br>            case &lt;-channels[0]:<br>            case &lt;-channels[1]:<br>            }<br>        default:<br>            select {<br>            case &lt;-channels[0]:<br>            case &lt;-channels[1]:<br>            case &lt;-channels[2]:<br>            case &lt;-or(append(channels[3:], orDone)...):<br>            }<br>        }<br>    }()<br>    return orDone<br>}</pre><p>Analyze detail:</p><h4>Base case:</h4><ul><li><strong>case 0</strong>: If there are no input channel, return nil.</li><li><strong>case 1</strong>: If there’s exactly one channel, just return it. There’s nothing to merge.</li></ul><h4><strong>Generate condition:</strong></h4><ol><li><strong>Create an output channel:</strong></li></ol><ul><li>Make <strong>orDone := make(chan struct{}{})</strong>. This is the single “merged” channel that will close as soon as any input channel closes.</li></ul><p>2. <strong>Spawn one goroutine to wait and close orDone:</strong></p><ul><li>Launch a goroutine whose sole job is to wait on the inputs and then <strong>close(orDone)</strong> when the first one fires. This keeps the caller’s stack clean and ensures <strong>orDone</strong> is closed exactly one.</li></ul><p>3. <strong>Inside that goroutines:</strong></p><ul><li><strong>defer close(orDone)</strong> guarantees the merged channel is closed on the first return path.</li><li>If there are exactly <strong>2 channels</strong>, a simple <strong>select</strong> on those two is enough.</li><li>If there are 3 or more: listen to the first three directly (channels[0], channels[1], channels[2] ), and for the rest (channels[3:]) make a recursive call: or(append(channels[3:], orDone)...).</li></ul><h4>Why append orDone to the recursive call?</h4><p>This is the key to avoiding goroutine leaks. When the <em>topmost</em> select returns and we close orDone, that same orDone is present in every deeper recursive level. Each waiting goroutine at lower levels also unblocks (because orDone closed), returns and exists. Without threading orDone down the tree, lower goroutines might keep waiting forever even though the result is already decided.</p><h4>How it behaves</h4><ul><li><strong>Correctness:</strong> orDone closes as soon as <em>any</em> input closes.</li><li><strong>Cancellation propagation:</strong> Closing orDone unblocks the entire recursion tree, preventing goroutine leaks.</li><li><strong>Nil-safety:</strong> Returning nil in the zero-channel case disables that branch in select, which is idiomatic.</li><li><strong>Cost:</strong> Uses O(n) goroutines in the worst case (one per recursive level), each waiting on a fixed small select, which is typically fine for “done” signals.</li></ul><p>The <strong>or-channel</strong> pattern is useful to employ at the intersection of modules in your system. At these intersections, you tend to have multiple conditions for canceling trees of gorou‐tines through your call stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02d04a6b2706" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>