<?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 Ayush Saxena on Medium]]></title>
        <description><![CDATA[Stories by Ayush Saxena on Medium]]></description>
        <link>https://medium.com/@ayushsaxena823?source=rss-f6d8b8192b44------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vbW14MktAWHCEdUd7Ppk7A.jpeg</url>
            <title>Stories by Ayush Saxena on Medium</title>
            <link>https://medium.com/@ayushsaxena823?source=rss-f6d8b8192b44------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:01:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayushsaxena823/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[Go Concurrency: How Go Runs 100,000 Goroutines on 11 Threads]]></title>
            <link>https://medium.com/@ayushsaxena823/go-concurrency-how-go-runs-100-000-goroutines-on-11-threads-42d70e2fad47?source=rss-f6d8b8192b44------2</link>
            <guid isPermaLink="false">https://medium.com/p/42d70e2fad47</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Ayush Saxena]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 05:37:24 GMT</pubDate>
            <atom:updated>2026-11-17T05:46:48.398Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into Go’s concurrency model, from OS threads to a real load tester.</em></p><figure><img alt="A Gopher chef rings a bell beside a long rail hung with order tickets, while other Gopher cooks work at their stations and three Gophers push a hopper that sprays out new orders." src="https://cdn-images-1.medium.com/max/1024/1*A-ydY8mshld1bkz_X3vH6w.png" /><figcaption>Many orders, a handful of execution resources</figcaption></figure><p>Hey there,</p><p>I recently went deep into Go’s internals and concurrency model, and built <a href="https://github.com/optimm/Gmeter">Gmeter</a>, an open-source, agent-friendly load tester for HTTP and gRPC.</p><p>It raised a few questions. How does Go manage thousands of goroutines? Who runs them? What happens when they wait for a network response? And how do they communicate without getting in each other’s way?</p><p>In one experiment on my 10-core machine, I created 100,000 waiting goroutines. The Go runtime reported creating only 11 OS threads. How is that possible?</p><p>Let’s start at the beginning.</p><h3>What is Go?</h3><p>Go (Golang) is a compiled, statically typed language from Google. It deliberately keeps its core small: packages, functions, structs, interfaces, explicit errors and garbage collection. The compiler emits native machine code, while the runtime handles memory management and goroutine scheduling. Its real distinction is built-in concurrency that is cheap enough to use casually.</p><h3>Why was Go introduced?</h3><p>Go was designed at Google in 2007 by Robert Griesemer, Rob Pike and Ken Thompson, and released in 2009. Google’s codebases were enormous, builds were slow, dependency management was painful, and multicore machines meant sequential code no longer got faster for free. Networked services also spent most of their time waiting on other systems.</p><p>C++ gave control but was heavy at scale; Python was easy to write but slow; Java already had garbage collection and threads. Go’s bet was the combination: a small compiled language, fast builds, cheap concurrent tasks and a standard library built for networking, so large systems stay easy to build, read and maintain.</p><h3>A little about Gmeter</h3><p>Gmeter is my open-loop load tester for HTTP and gRPC, built for developers and AI agents.</p><p>Most testers are closed-loop: they wait for a reply before sending the next request, so a slowing server quietly gets asked for less and the numbers flatter it. Gmeter keeps its own clock: it stays on the rate you asked for, times each request from when it should have gone out rather than when a slot freed up, and flags when the load generator itself is the bottleneck.</p><p>Gmeter is also a practical example of Go’s concurrency model. We’ll open up its architecture once we understand the goroutines, channels and scheduler underneath.</p><p>Code and docs: <a href="https://github.com/optimm/Gmeter">GitHub</a> · <a href="https://optimm.github.io/Gmeter/">website</a>.</p><h3>Concurrency is not parallelism</h3><p>Concurrency is structuring a program as independently progressing tasks that don’t block one another. Parallelism is executing several tasks at the same instant on multiple CPU cores.</p><p>Picture one chef with three orders: pizza in the oven, pasta boiling, vegetables on the board. Three dishes are in progress, but only one pair of hands moves at any instant. That’s concurrency. Add two more chefs and dishes can progress simultaneously. That’s parallelism which is why an HTTP server can serve many requests: while one waits on a database, the CPU makes progress on the next.</p><h3>Why not just create more threads?</h3><p>The OS schedules threads onto available CPUs. Each thread has its own stack, registers and instruction pointer, and shares the process address space. Switching threads means saving one context and restoring another, like bookmarking a book, and it also disturbs CPU cache locality.</p><p>Picture 10,000 orders, one chef each. Most just stand at an oven while still taking up kitchen space. Threads cost the same way: megabytes of reserved stack, kernel resources, plus creation and scheduling overhead. A parked thread burns no CPU but still holds memory. Thread pools and event loops are the usual workarounds; Go offers goroutines.</p><figure><img alt="Three-panel cartoon. One thread per order shows hundreds of exhausted Gopher chefs each standing at a single oven. Goroutines shows one Gopher pulling tickets from a rail while a few cheerful chefs share the stations, ending with a Gopher proudly presenting plated dishes." src="https://cdn-images-1.medium.com/max/1024/1*Suyue6ma0aMfzR6UndUKZw.png" /><figcaption>One thread per order versus a pool of chefs</figcaption></figure><p>These costs matter most for I/O-bound work. If each of 10,000 connections spends 99% of its life waiting on the network, a dedicated thread each is waste. CPU-bound work is different: more work units than cores won’t finish faster. So keep the number of operations in progress separate from the resources that execute them.</p><h3>Goroutines: a task is not a thread</h3><p>A goroutine is a lightweight unit of execution managed by the Go runtime. Prefix any function call with go:</p><pre>go processRequest()</pre><p>The caller keeps going without waiting. But if main returns, the program exits. A sync.WaitGroup lets us wait for goroutines to finish instead.</p><p>Think of a goroutine as an order ticket, not a chef: it starts with a ~2 KB stack that grows and shrinks as needed. The runtime tracks it in a g struct holding the stack, saved context, state and scheduling info, and can move the stack because the compiler knows where its pointers are on it. Unlike a thread, creating a goroutine never enters the kernel, and switching between goroutines is a user-space jump rather than an OS context switch.</p><p>Let’s measure that</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc492d0df392af54df9a06a56bb322b3/href">https://medium.com/media/cc492d0df392af54df9a06a56bb322b3/href</a></iframe><p>My run: 100,001 goroutines (including main), 11 OS threads, ~205 MB of stack for the waiters. Numbers vary by machine, Go version and workload. None of those 100,000 goroutines are actually running; they’re waiting.</p><p>So who decides which goroutine runs?</p><h3>The Go scheduler: G, M and P</h3><p>Go uses M:N scheduling: the runtime multiplexes many goroutines onto fewer OS threads, using three entities:</p><ul><li>Order ticket → <strong>G: goroutine</strong></li><li>Chef → <strong>M: OS thread</strong></li><li>Cooking station with a ticket rail → <strong>P: logical processor</strong></li><li>Order waiting on an oven → <strong>waiting goroutine</strong></li></ul><p>Kitchen version: many tickets, a few chefs and a few stations. A chef needs a station to cook, and when an order waits on the oven, they set its ticket aside and take another.</p><p>A P isn’t a physical CPU. It supplies the resources and local runnable queue an M needs to execute ordinary Go code. GOMAXPROCS sets the number of Ps (by default, the number of CPUs), not threads or goroutines. Only an M holding a P can run Go code, which is why extra threads alone don&#39;t add parallelism. The OS still schedules Ms onto CPUs.</p><p>In the experiment above, ten of those 11 threads match the 10 Ps on my machine; the rest are runtime housekeeping, not one thread per goroutine.</p><figure><img alt="Diagram: a global runnable queue feeds three local queues on processors P0, P1 and P2, each holding three goroutines. Each P is attached to an OS thread, M0 to M2, which runs on a CPU. Idle processors can steal runnable goroutines from another local queue." src="https://cdn-images-1.medium.com/max/1024/1*vv3lILaYYBzv8froK11fuw.png" /><figcaption>G-M-P scheduler architecture</figcaption></figure><p>With GOMAXPROCS=4, four Ps allow up to four threads to run Go code at once, even alongside hundreds of runnable goroutines and extra Ms blocked in system calls. Runnable goroutines, Ps and Ms are three different counts: at any moment you might have 500 runnable goroutines, 4 Ps and 12 Ms.</p><p>Writing go f() makes a goroutine runnable; an M holding a P eventually picks it up.</p><h3>What happens if a goroutine needs to wait?</h3><p>When a goroutine waits on a channel, timer or supported network operation, the runtime parks it, and the thread runs another goroutine. When the event arrives, the first goroutine becomes runnable again, not necessarily on the same thread. gopark and goready drive those transitions. Runnable means eligible to run, not running right now.</p><p>Kitchen version: the order goes into the oven, the chef sets the ticket aside, and the timer puts it back in the queue when it’s done.</p><figure><img alt="State diagram: go f() makes a goroutine Runnable and the scheduler marks it Running. A Running goroutine returns and becomes Finished, parks into Waiting, or is preempted back to Runnable. A Waiting goroutine wakes back to Runnable." src="https://cdn-images-1.medium.com/max/1024/1*p_c8BWjRTFsfYg22SnQy4Q.png" /><figcaption>Goroutine lifecycle</figcaption></figure><h3>Work stealing and preemption</h3><p>Each P has a local runnable queue, plus a global queue; an idle P steals from a busy one, spreading work without contending on a single central queue.</p><p>In the kitchen, if one station has 100 pending orders and the next has none, the chef at the idle station takes tickets from the busy one’s rail.</p><p>A goroutine that computes for a long time without yielding doesn’t get to hog a P either: modern Go preempts it asynchronously at safe points. Not a real-time guarantee, but it prevents starvation.</p><p>In the kitchen, a chef lost in chopping eventually gets a tap on the shoulder so other tickets get a turn.</p><h3>Network I/O: waiting without dedicating a thread</h3><p>If you read my <a href="https://medium.com/@ayushsaxena823/what-is-redis-and-how-does-it-work-cfe2853eb9a9">blog on Redis</a>, you’ll remember I/O multiplexing.</p><p>Consider http.Get(url). The goroutine waits for the response. Does its thread have to stay blocked for the whole time?</p><p>No. Go’s network poller uses non-blocking sockets plus epoll on Linux and kqueue on macOS. When a socket can&#39;t make progress, the runtime parks the goroutine; when the OS reports readiness, it becomes runnable.</p><p>Kitchen version: suppliers arrive at different times, so instead of one chef per entrance, the kitchen keeps a clipboard of expected deliveries and listens for the doorbell.</p><figure><img alt="Two-panel cartoon. On the left a frustrated Gopher chef waits empty-handed by the delivery door as a clock ticks. On the right the same chef happily stir-fries, the doorbell lit, showing other work continues during the wait." src="https://cdn-images-1.medium.com/max/1024/1*rgMWrDt_rvUAYolsaF5zcA.png" /><figcaption>Waiting for the network meme</figcaption></figure><p>A read returns a would-block result instead of sleeping in the system call, and the poller waits for readiness before retrying it. That’s not the same as sitting in one kernel call for an entire HTTP response. With HTTP/1.1, net/http may also use separate read and write goroutines per persistent connection, with the application goroutine waiting on their coordination channels.</p><figure><img alt="Flowchart: a socket read that would block parks the goroutine while its thread runs other work. A kernel notification from epoll or kqueue then marks the goroutine runnable, and it retries the read when scheduled." src="https://cdn-images-1.medium.com/max/1024/1*7hFrkaAT0hJnff8LE3xldQ.png" /><figcaption>Network poller architecture</figcaption></figure><figure><img alt="A Gopher in a headset watches a wall panel of indicator lights with one lit, saying epoll: your delivery is ready, while another Gopher chef packs a takeaway bag." src="https://cdn-images-1.medium.com/max/1024/1*_w3MvBd4fx31G7SQqFcVHQ.png" /><figcaption>epoll delivery notification meme</figcaption></figure><p>The result: synchronous-looking application code with asynchronous network waiting underneath. Not every system call works this way. For genuinely blocking ones, the runtime can hand the available P to another M.</p><h3>Channels: how do goroutines communicate?</h3><p>A channel is a typed conduit between goroutines: one side sends, the other receives, and the runtime handles the hand-off.</p><pre>direct := make(chan string)<br>buffered := make(chan string, 10)</pre><p>The first is unbuffered: a send waits for a receiver. The second is buffered: a send proceeds while there’s space, and waits once the buffer is full.</p><p>Kitchen version: a waiter passes orders to chefs. With no rail, every order is handed over directly. A rail that holds ten tickets lets the waiter leave orders and keep moving until it fills.</p><h3>Sending and receiving values</h3><p>Channels are typed: chan int carries integers, chan job carries jobs; a mismatch fails at compile time. The arrow points where the value goes:</p><pre>ch &lt;- 42       // send 42 to ch<br>value := &lt;-ch  // receive from ch</pre><p>An unbuffered channel is a rendezvous. Here main waits for a greeting from a worker:</p><pre>func main() {<br>    greetings := make(chan string)<br>    go func() {<br>        greetings &lt;- &quot;Hello from a goroutine&quot;<br>    }()<br>    fmt.Println(&lt;-greetings)<br>}</pre><p>Whoever arrives first waits for the other: main waits for a sender, or the worker waits for a receiver. Neither polls; the runtime parks and wakes them. That’s why channels are both communication and synchronisation primitives.</p><h3>Buffered channels and capacity</h3><p>A buffer of two instead of a direct hand-off:</p><pre>jobs := make(chan int, 2)<br>jobs &lt;- 1  // succeeds without a receiver<br>jobs &lt;- 2  // succeeds; the buffer is full<br>fmt.Println(&lt;-jobs) // 1; frees a slot<br>jobs &lt;- 3  // succeeds again<br>fmt.Println(&lt;-jobs) // 2<br>fmt.Println(&lt;-jobs) // 3</pre><p>Sending a third value before that first receive would block, and deadlock if nothing else in the program could receive. Receiving from an empty channel waits for a sender, unless the channel is closed.</p><figure><img alt="Diagram: a producer sending 3 waits because the buffer is full, holding 1 and 2. A receiver takes 1 and frees a slot, so the producer resumes and the buffer holds 2 and 3." src="https://cdn-images-1.medium.com/max/1024/1*fM3XpXBvZ1X5xpk_v9W36Q.png" /><figcaption>Buffered channel backpressure</figcaption></figure><p>cap(jobs) is the capacity and len(jobs) the current count. Treat len as a snapshot: with concurrent senders and receivers it can change immediately, so it&#39;s no substitute for a safe send or receive.</p><p>A bigger buffer absorbs bursts but doesn’t speed up consumers. Produce 1,000 requests per second and consume 800, and 1,000 slots fill in about five seconds. Then the producer waits or work is rejected or dropped.</p><h3>Backpressure and channel internals</h3><p>That’s backpressure: a bounded queue turns an overloaded consumer into a visible slowdown of the producer instead of unlimited memory growth. In the kitchen, a full rail means the waiter stops taking new orders instead of stuffing them into a pocket.</p><p>Inside, a channel is an hchan: a circular buffer where applicable, queues of waiting senders and receivers, and a lock over its state. If a receiver is already waiting, the value is handed over directly. A send that can&#39;t proceed parks the sender until a match wakes it.</p><p>Three cases on send:</p><ul><li><strong>A receiver is waiting:</strong> transfer the value to the receiver and make it runnable.</li><li><strong>Buffer has space:</strong> copy the value into the circular buffer.</li><li><strong>Buffer is full:</strong> park the sender until progress is possible.</li></ul><p>The circular buffer keeps read and write indices that wrap as slots are reused. When a receive frees a slot, the runtime delivers the oldest value and refills the slot from a waiting sender. Waiting goroutines are linked to their operations through runtime records often called sudog. These are implementation details, not guarantees.</p><p>Channels also order memory: a send happens before its matching receive completes. But sending a pointer doesn’t make the pointee safe to modify concurrently. Ownership still matters.</p><h3>Closing a channel</h3><p>Closing a channel signals that no more values will be sent. Buffered values stay readable until drained.</p><pre>jobs := make(chan int, 2)<br>jobs &lt;- 1<br>jobs &lt;- 2<br>close(jobs)<br>for job := range jobs {<br>    fmt.Println(job) // 1, then 2<br>}</pre><p>Closing doesn’t discard buffered values. Once drained, receives return the zero value with ok == false and range ends. Sending to a closed channel, or closing twice, panics. Let the producer that owns all sends coordinate closure. A nil channel is different: sends and receives block forever. In kitchen terms, the cooks stop accepting orders but still finish the tickets on the rail.</p><h3>Waiting for more than one event with select</h3><p>select waits on multiple channel operations and runs whichever becomes ready first:</p><pre>select {<br>case job := &lt;-jobs:<br>    process(job)<br>case &lt;-ctx.Done():<br>    return<br>}</pre><p>This assumes jobs stays open; otherwise use job, ok := &lt;-jobs and return when !ok. If several cases are ready, Go picks one pseudo-randomly. A default case makes select return immediately when nothing can proceed; without it, the goroutine parks until an operation is ready. In the kitchen, it&#39;s a chef who must either take the next order or answer the closing bell.</p><p>A goroutine parked forever on a channel that nobody will ever send to is a goroutine leak: it never exits and its stack is never freed. Closing a channel or cancelling a context is how you release those waiters.</p><h3>Race conditions, mutexes and atomics</h3><p>Channels are not the only synchronisation mechanism. A data race happens when two goroutines touch the same memory concurrently and at least one writes, with no synchronisation between them.</p><pre>var completed atomic.Uint64<br>// Multiple goroutines may safely call:<br>completed.Add(1)<br>fmt.Println(completed.Load())</pre><p>An increment is a read-modify-write sequence. Two chefs updating the same completed-order counter show why that matters: both read 10, both write 11, so two orders are done but one is recorded. Atomics suit simple counters; a sync.Mutex suits several fields that must change together under an invariant; a sync.WaitGroup waits for a group of workers to exit. go test -race ./... detects races your tests exercise, but passing doesn&#39;t prove every execution is race-free. A rough rule: use channels to pass ownership or signal between goroutines, and mutexes to protect state they already share.</p><h3>Back to Gmeter: what does a load tester need?</h3><p>Say we want 1,000 HTTP requests per second. A naive approach:</p><pre>for {<br>    sendRequest()<br>    time.Sleep(time.Millisecond)<br>}</pre><p>If a request takes 200 ms, this loop manages fewer than five per second, because the server’s latency dictates our request rate. Deciding when a request is due has to be separate from executing it.</p><p>Gmeter uses a scheduler, a bounded jobs channel and a worker pool, plus a sampler for live metrics and an optional writer that records individual samples to CSV. Worker tallies are merged at the end.</p><figure><img alt="Architecture diagram: a scheduler with intended send times feeds a bounded jobs channel sized to the worker count, which feeds a pool of workers. Workers send requests to the target HTTP service and record results into worker-local tallies, which a live sampler samples and which merge after a WaitGroup." src="https://cdn-images-1.medium.com/max/1024/1*rLdH2cauvOC0JOSOaLLJ1A.png" /><figcaption>Gmeter architecture</figcaption></figure><p>Each job keeps its intended execution time: the scheduler follows the clock, while workers pick jobs independently and wait on HTTP responses.</p><p>The pool is created once instead of starting an unbounded goroutine per request:</p><pre>jobs := make(chan job, cfg.Workers)<br>var wg sync.WaitGroup<br>for _, t := range tallies {<br>    w := &amp;worker{client: client, cfg: cfg, t: t}<br>    wg.Go(func() { w.run(ctx, jobs) })<br>}</pre><p>A simplified excerpt of the runner, using WaitGroup.Go (Go 1.25). Every worker receives from the same channel but owns its tally independently, and the capacity equals the worker count, bounding the pending queue.</p><pre>func (w *worker) run(ctx context.Context, jobs &lt;-chan job) {<br>    for j := range jobs {<br>        w.do(ctx, j)<br>    }<br>}</pre><p>When the channel fills, the scheduler can block, but it keeps each job’s original due time rather than shifting the schedule. Cancellation lets it stop instead of getting stuck.</p><p>Its core loop:</p><pre>loop:<br>for {<br>    at, stage, ok := sched.Next()<br>    if !ok { break }<br>    // Wait until the intended send time.<br>    pacer.WaitUntil(schedCtx, at, spin)<br>    select {<br>    case jobs &lt;- job{at: at, stage: stage, seq: seq}:<br>        seq++<br>    case &lt;-schedCtx.Done():<br>        break loop<br>    }<br>}<br>close(jobs)<br>wg.Wait()</pre><p>Illustrative, with error, accounting and cancellation details omitted. At light load an idle worker gets a job with little queueing; under load, jobs wait in the buffer; at saturation the scheduler itself waits on the channel. When it resumes, deadlines may already be past, so it catches up while keeping the original times. That’s deliberate: a load tester must expose its own scheduling delays.</p><p>The pacer combines timer-based waiting with a short, configurable spin near the deadline. Timers can fire late; spinning tightens precision at the cost of CPU, so it’s bounded rather than used across the whole interval.</p><h3>How many workers do we need?</h3><p>At 1,000 requests per second with 200 ms average service, Little’s Law gives 1,000 × 0.2 = 200 requests in flight, plus headroom for fluctuations. More workers alone can’t overcome CPU, network, connection or server bottlenecks.</p><h3>Avoiding shared state</h3><p>A shared histogram would put every worker behind one mutex even though workers rarely read each other’s data. Gmeter keeps one tally per worker instead, avoiding that contention on the hot path, then merges them after a WaitGroup confirms every worker has exited. That merge is also the synchronisation boundary for reading their writes.</p><p>Kitchen version: two hundred chefs sharing one notebook would still queue even with a lock. Give each their own and combine them at the end.</p><p>Live shared counters use atomics, and the histogram recorder supports concurrent sampling with a single writer and atomic fields; snapshots needn’t be perfectly instantaneous. Ownership is a better starting point than locking everything.</p><h3>Sampling, backpressure and cancellation</h3><p>The sampler polls metrics on its own schedule instead of relying on workers to report progress. A stalled worker can’t report reliably, which is exactly when you need visibility. It waits on a ticker and a stop signal via select. Individual samples can also flow through a buffered channel to a dedicated CSV writer; if the disk can&#39;t keep up, the buffer fills and backpressure becomes visible.</p><pre>for {<br>    select {<br>    case now := &lt;-tick.C:<br>        sample(now)<br>    case &lt;-done:<br>        return<br>    }<br>}</pre><p>Kitchen version: a manager checking in periodically rather than trusting chefs to send updates.</p><p>The sampler owns its timeline while running: stop closes a signal channel, then waits for a second channel confirming exit, so the caller can safely read the completed timeline. The CSV writer similarly keeps draining queued samples after a write error, so producers never hang on a full buffer.</p><p>On stop, the scheduler closes the jobs channel; workers finish or observe cancellation; the runner waits for them before collecting results. Contexts propagate cancellation to HTTP work, while channels and WaitGroups provide the ownership and shutdown boundaries.</p><h3>Coordinated omission: the missing latency</h3><p>Coordinated omission is the bias you get when latency is measured only from the moment a request is actually sent. If the generator falls behind, the slowest experiences stop being observed. It’s called coordinated because the generator’s request pattern coordinates with the server’s stalls, quietly hiding them.</p><p>A closed-loop tester does exactly that: it sends the next request only after the previous one finishes, so a stalled server produces fewer requests and hides the delays real users would have suffered.</p><p>Metro version: passengers arrive every second and the train is a minute late. Time their trip from boarding and you’ve hidden their wait on the platform.</p><p>Gmeter follows an open-loop schedule: a request keeps the timestamp at which it was due, even when workers are busy and the queue is full.</p><figure><img alt="Two-panel cartoon. On the left a crowd of angry Gophers waits on a platform holding stopwatches, shouting we waited 300 ms as the train arrives. On the right a single Gopher relaxes on the train with a clipboard, saying great, only 20 ms." src="https://cdn-images-1.medium.com/max/1024/1*XjzK7OTRS5aRPrqNHxM3xA.png" /><figcaption>Coordinated omission meme</figcaption></figure><ul><li><strong>Scheduled request time:</strong> 0 ms</li><li><strong>Actual send:</strong> 300 ms</li><li><strong>Completion:</strong> 320 ms</li></ul><p>Service time = 320–300 = 20 ms.</p><p>Corrected latency = 320–0 = 320 ms.</p><p>The server-facing operation took 20 ms; the scheduled request took 320 ms. Corrected latency makes that delay visible. It also includes load-generator delay, so monitor worker saturation and other client-side limits rather than automatically blaming the server.</p><figure><img alt="Timeline from due time 0 ms to sent at 300 ms to done at 320 ms. A 300 ms queue delay is followed by 20 ms of service time, giving a corrected latency of 320 ms." src="https://cdn-images-1.medium.com/max/1024/1*fzkMIqHaSt9CK9e8jcAkkQ.png" /><figcaption>Corrected versus service latency</figcaption></figure><p>Small example: a target normally responds in 10 ms but stalls for a second. A closed-loop generator may record a single slow observation. If arrivals were intended every 100 ms, many more requests were due during that stall; measuring from those intended timestamps exposes the backlog’s wait without pretending the server received requests that were never sent.</p><h3>Bringing everything together</h3><p>Follow one request through Gmeter. The scheduler waits for its due time. A channel hands the job to a worker, which starts the HTTP I/O; while its goroutines wait, other work runs, and the network poller wakes them when I/O is ready. The worker records latency and moves on, while the sampler watches independently.</p><p>Building Gmeter taught me that concurrency is less about starting goroutines and more about who owns data, which operations can block, what happens when consumers fall behind, and how everything shuts down.</p><p>Go gives us remarkably simple primitives for those decisions. Underneath is a rather sophisticated runtime.</p><p>I hope this helped you see a little of what happens behind that deceptively small go keyword.</p><p>Happy learning!</p><p><a href="https://github.com/optimm/Gmeter">Explore Gmeter on GitHub</a></p><h3>References</h3><ul><li><a href="https://go.dev/talks/2012/splash.article">Go at Google: language design</a></li><li><a href="https://go.dev/doc/effective_go#concurrency">Effective Go: concurrency</a></li><li><a href="https://go.dev/src/runtime/proc.go">Go runtime scheduler source</a></li><li><a href="https://go.dev/src/runtime/chan.go">Go runtime channel source</a></li><li><a href="https://go.dev/ref/spec#Channel_types">Go language specification: channels</a></li><li><a href="https://go.dev/ref/mem">Go memory model</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42d70e2fad47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Redis and how does it work Internally]]></title>
            <link>https://medium.com/@ayushsaxena823/what-is-redis-and-how-does-it-work-cfe2853eb9a9?source=rss-f6d8b8192b44------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfe2853eb9a9</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Ayush Saxena]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 12:15:46 GMT</pubDate>
            <atom:updated>2024-03-10T18:59:20.173Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there, In this blog we will learn about redis and its internal working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXRpfdfV6IFq633yPRoi7g.jpeg" /></figure><h3>Caching</h3><p>Let us start with talking about caching. In the world of computer science and software development, caching is like having a <strong>quick-access memory</strong> for frequently used information. Imagine you have a favourite snack that you always keep within arm’s reach instead of going to the store every time you crave it. Caching works in a similar way, allowing applications to keep a handy copy of <strong>frequently needed data</strong> in a special storage area known as a cache.</p><p>The main goal of caching is to speed things up. Instead of repeatedly going back to the original source for data, which might be slow or resource-intensive, the application can fetch it from the nearby cache. This quick retrieval helps save time and resources, making the whole process more efficient. One other thing about caching is that we cache only the data that does not change very frequently as that would hinder with the purpose of not having to access the DB frequently.</p><p><strong>You may find it weird that why am i discussing why redis before what is redis, hold on and you will get it.</strong></p><h3>Why Redis ?</h3><p>Now that we’ve grasped the importance of storing data efficiently for quick access, let’s tackle the question: Why choose Redis as the datastore for caching, and not any other options like MySQL or MongoDB?</p><p>The answer lies in how Redis does the job. Redis is designed specifically for speed. It’s an <strong>“in-memory” database</strong>, storing data right in your computer’s active memory (RAM). This makes retrieving data lightning-fast because it’s already in the workspace where your computer actively operates.</p><p>On the other hand, traditional databases like MySQL or MongoDB store data on secondary storage, like a hard drive. While effective for many tasks, fetching data from secondary storage takes more time compared to fetching it from active memory (RAM). It’s like choosing between grabbing a book from a shelf or having a cheat sheet always open on your desk. <br>Accessing data in memory is significantly faster than performing random disk I/O, contributing to the low latency and high throughput observed in Redis caching. An additional advantage stems from the ease of implementing data structures in memory compared to their on-disk counterparts.</p><p><strong>I hope now this gives the answer to why redis and why this question was important.</strong></p><blockquote>In the realm of computer memory, registers and CPU cache are the speedsters, faster than RAM. Found within the processor, they operate at lightning speed. However, due to their high cost and limited capacity, they’re like the Formula 1 racers of memory — incredibly fast but reserved for the most critical tasks. For everyday use and storing larger amounts of data, RAM and in-memory databases like Redis take the lead.</blockquote><h3>What is Redis ?</h3><p>Quoting the redis docs</p><p><em>Redis is an open source (BSD licensed), in-memory data structure store used as a database, cache, message broker, and streaming engine. Redis provides </em><a href="https://redis.io/docs/data-types/"><em>data structures</em></a><em> such as </em><a href="https://redis.io/docs/data-types/strings/"><em>strings</em></a><em>, </em><a href="https://redis.io/docs/data-types/hashes/"><em>hashes</em></a><em>, </em><a href="https://redis.io/docs/data-types/lists/"><em>lists</em></a><em>, </em><a href="https://redis.io/docs/data-types/sets/"><em>sets</em></a><em>, </em><a href="https://redis.io/docs/data-types/sorted-sets/"><em>sorted sets</em></a><em> with range queries, </em><a href="https://redis.io/docs/data-types/bitmaps/"><em>bitmaps</em></a><em>, </em><a href="https://redis.io/docs/data-types/hyperloglogs/"><em>hyperloglogs</em></a><em>, </em><a href="https://redis.io/docs/data-types/geospatial/"><em>geospatial indexes</em></a><em>, and </em><a href="https://redis.io/docs/data-types/streams/"><em>streams</em></a><em>. Redis has built-in </em><a href="https://redis.io/topics/replication"><em>replication</em></a><em>, </em><a href="https://redis.io/commands/eval"><em>Lua scripting</em></a><em>, </em><a href="https://redis.io/docs/reference/eviction/"><em>LRU eviction</em></a><em>, </em><a href="https://redis.io/topics/transactions"><em>transactions</em></a><em>, and different levels of </em><a href="https://redis.io/topics/persistence"><em>on-disk persistence</em></a><em>, and provides high availability via </em><a href="https://redis.io/topics/sentinel"><em>Redis Sentinel</em></a><em> and automatic partitioning with </em><a href="https://redis.io/topics/cluster-tutorial"><em>Redis Cluster</em></a><em>.</em></p><p>Now, for a deeper dive into Redis’s capabilities and usage, the Redis documentation is your go-to resource. You can explore data stores, learn how to harness the power of Redis. We’ll discuss data persistence in Redis in some other blog.</p><p><strong>An intriguing fact about Redis:</strong> It operates on a single-threaded model. Surprising, right? Stick around as we uncover the mysteries behind Redis’s remarkable performance, including how it thrives with just one thread.</p><h3>Single-Threaded Redis</h3><p>You might be wondering: why would Redis, opt for a single-threaded design? Wouldn’t it be more efficient to utilise multiple threads and tap into all available CPU cores for parallel computation?</p><p>The answer lies in the nature of Redis’s workload. Redis is like a chef in a computer kitchen, handling one task at a time to ensure perfection. While many helpers might sound good, for Redis, it prefers a single thread for precision, avoiding chaos and ensuring each task is flawlessly executed.</p><p>While many applications benefit from parallel processing, Redis primarily focuses on quick data access and minimal latency. A single-threaded approach simplifies the design, ensuring that commands are executed sequentially without the complexities of managing multiple threads and potential synchronisation issues.</p><p>In Redis, each command is executed atomically, guaranteeing consistency. This simplicity contributes to faster execution, as the single thread can fully utilise the CPU cache, minimising cache misses and optimising performance.</p><blockquote>In a multi-threaded environment, threads share certain resources, including the CPU cache. When one thread updates data, it may cause the cache to be updated or invalidated. If another thread was using the same data or related data, it might experience what is known as a “cache miss” because the data it needs is no longer in the cache or has been modified.</blockquote><blockquote>This situation creates what we call cache contention or cache thrashing, where threads are competing for access to the same limited cache space. Instead of a smooth flow of data, you get interruptions and inefficiencies as threads contend for access, leading to potential performance bottlenecks.</blockquote><p><strong>Okay, we’ve grasped why Redis opts for a single-threaded approach. But here’s the intriguing question: How does a single thread manage many thousands of incoming requests and outgoing responses simultaneously? Wont the thread get blocked in completing each request individually?</strong></p><h3>Managing Thousands in Harmony</h3><p>Here’s where I/O multiplexing comes into the picture — it’s the secret sauce that helps Redis achieve apparent concurrency. Seems like a buzzword, doesn’t it? Let me break it down for you.</p><p>Here are the steps</p><ul><li><strong>Redis Server is Running at Some Address:</strong> Redis, like a diligent worker, is up and running, ready to handle requests and share its data.</li><li><strong>Redis Accepts Multiple TCP Connections Through Clients:</strong> As various clients, which could be applications or services, want to interact with Redis, they establish TCP connections. Now a network socket is established between redis and the client. A network socket is a virtual communication channel between the client and Redis. It’s like a two-way street where data can flow in both directions.</li><li><strong>Without I/O Multiplexing: </strong>To read data from a network socket, Redis initiates a read() system call . This read system call, functioning as an I/O operation, is characterised by its blocking nature, meaning Redis’s single-threaded process will wait on the associated TCP connection until data becomes available to read. This data typically consists of requests and corresponding data sent by clients to Redis. This blocking behaviour implies that Redis, with its single-threaded nature, would be confined to processing only one TCP connection at a time. The Redis server’s thread would wait on a specific client’s connection until data is ready to be read and thus there would be no point of accepting multiple connections.</li></ul><blockquote>Does any solution of this problem come to your mind : can we not do something that we should fire a request to read only when we know that the data is ready to be read and thus avoid the blocking nature , can we not receive some sort of alert that hey your data is ready please read and process. You are right this is exactly what I/O multiplexing does.</blockquote><h3>I/O Multiplexing</h3><ul><li>I/O multiplexing allows Redis to monitor multiple connections simultaneously without blocking its main thread. Instead of waiting for data on a single connection, Redis can keep an eye on multiple connections at once.</li><li>Redis uses the select() or poll() system call to register interest in multiple sockets (connections) simultaneously. These calls allow it to specify a set of sockets it wants to monitor for specific events, such as readiness to read.</li><li>This select() or poll() system calls fall under the umbrella of I/O monitoring system calls.</li><li>Redis’s single thread invokes the select() or poll() system call and enters a state of waiting for events. During this time, Redis is not actively processing any specific connection; instead, it awaits notifications about events on the registered sockets and process the requests from the ready sockets one at a time.</li></ul><blockquote>Here you might say that if it is processing requests one at a time only then how is the efficiency achieved, Redis beautifully exploits the fact that network I/O is much time taking then Redis’s in-memory operations (which are atomic) and thus redis can provide high throughput, low latency and this apparent but performant concurrency.</blockquote><ul><li>When an event occurs on any of the registered sockets (e.g., data becomes available for reading), the select() or poll() call returns. The return value indicates which sockets experienced events, allowing Redis to identify where data is ready to be processed.</li><li>Redis then proceeds to handle the specific events on the sockets identified by the system call. For example, if data is ready to be read on a particular socket, Redis can initiate the read operation without waiting, addressing the blocking nature of traditional I/O.</li><li>The event-driven approach is asynchronous; Redis doesn’t actively poll each socket but rather responds to events as they occur. This allows Redis to efficiently manage a large number of connections without wasting resources on constant polling.</li><li>By waiting for events rather than blocking on individual sockets, Redis maximizes the utilisation of its single thread and system resources. This ensures that the server remains responsive to events across multiple connections without unnecessary delays.</li></ul><h3>I/O Monitoring System Calls</h3><p>I/O monitoring system calls are functions provided by the operating system that allow your program to keep an eye on multiple input/output sources, like file descriptors or network sockets, at the same time.</p><p>Think of I/O monitoring as setting up a watchman for your program. You tell the watchman what you’re interested in (readiness to read, write, etc.), and then your program takes a break, letting the watchman keep an eye on things. When an event happens, the watchman signals your program, saying, “Hey, something’s ready!” Your program then jumps back in to handle the specific event.</p><p><strong><em>Hope you liked it, Drop a 👏 and do follow for more content</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfe2853eb9a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Summer of Bitcoin Story]]></title>
            <link>https://medium.com/@ayushsaxena823/my-summer-of-bitcoin-story-4f576b03ad03?source=rss-f6d8b8192b44------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f576b03ad03</guid>
            <category><![CDATA[summer-of-bitcoin]]></category>
            <category><![CDATA[eye-of-satoshi]]></category>
            <category><![CDATA[summer-internships]]></category>
            <dc:creator><![CDATA[Ayush Saxena]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 08:29:43 GMT</pubDate>
            <atom:updated>2024-03-07T17:58:17.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Eye of satoshi" src="https://cdn-images-1.medium.com/max/125/1*uyR5FR36EmYvm5Vc7PcLFQ.png" /><figcaption>Eye of satoshi</figcaption></figure><h3><strong>The Beginning</strong></h3><p>I was looking for summer internships and came across the Summer of Bitcoin program. I was interested in Rust programming, and that’s how I found Eye of Satoshi. The people in the community were really friendly, and one person, my mentor Sergi, stood out. He patiently answered all my questions, even the ones that might have seemed silly. The community made me feel like I belonged. It was okay to ask simple questions, and this made me comfortable to learn and try new things without worrying about making mistakes. This experience taught me that it’s not just about finding an internship; it’s about finding a group of people who support you. Eye of Satoshi and the Summer of Bitcoin program were exactly that.</p><h3><strong>The Proposal</strong></h3><p>I enjoy making web apps, so I picked the web-based GUI project. I set up the watchtower and completed the project’s competency tests to show my skills. The project was marked easy, I knew there would be lots of competition. But I believed in myself and decided to write a proposal that was really detailed and thorough, something that not everyone might do.</p><p>I didn’t let the tough competition discourage me. Instead, I saw it as a challenge and worked hard on my proposal. I wanted it to stand out. So, I spent a lot of time making sure every part of the proposal was well-done and clear.</p><p>When I finished it, I sent in my proposal. This whole process, from picking the project to submitting the proposal made me believe more in hard work.</p><h3><strong>The Selection</strong></h3><p>When I found out I was chosen, I felt really happy and also a bit nervous. I started thinking about how to do different parts of the project, and it made my mind busy. I took a moment to relax and then I called my parents. I wanted to tell them about this good news. When I talked to my parents, they were excited too. Their happiness made me feel better. It was like they were with me on this journey. Sharing my success with them helped me feel more excited and ready for the new adventure ahead.</p><h3><strong>The Onboarding</strong></h3><p>The program kicked off, and the onboarding process began. I was filled with excitement as I looked forward to connecting with people and contributors from different corners of the world. It was amazing to think about the diverse group of individuals I was about to meet. I want to express my gratitude to Adi for the exceptional onboarding process. Adi made everything smooth and exciting, guiding us through every step of the program. Their support and assistance played a significant role in making this journey even more enjoyable and rewarding.</p><h3><strong>My Summers</strong></h3><p>This summer has been incredibly exciting for me. I’ve never worked this hard before, as I found myself juggling between my project and getting ready for college placements.</p><p>It’s been quite the adventurous summer, to say the least. I began my project by laying out the architecture. I spent time studying design patterns, best coding practices, and project structures.</p><p>In the initial phase, I focused on the project’s backend. I developed APIs and paid special attention to keeping my code adaptable and easy to maintain. I delved into testing and ensured that I wrote unit tests to cover all parts of the backend.</p><p>Certain parts of the project needed a big chunk of my time, and I ended up doing a lot of research and figuring out solutions to problems. These challenges taught me the most important lessons. Sometimes, certain parts of the project took more time than I thought they would. I had to overcome obstacles by searching a lot and trying different things to fix issues. Even though it was tough and sometimes frustrating, it was also really satisfying. Every time I faced a problem, I not only found a solution but also learned better ways to solve problems. It’s like they say: the hardest challenges teach you the most valuable things.</p><p>Aside from the primary project, I took on the task of enhancing the command-line interface (CLI) of the watchtower. During this process, I identified areas in error handling and logging that could be significantly improved. With my sleeves rolled up, I analyzed the existing setup, outlined the potential enhancements, and then dedicated myself to implementing these changes.</p><p>With the first half of the summer behind me and after excelling in the mid-term evaluations, I moved on to the frontend. I wanted to create a clean and user-friendly UI, so I learned how to use Figma for designing. Once I had the UI designed, I got feedback from my mentor and then started coding the frontend.</p><p>Throughout this journey, my experience has been fantastic. Regular meetings with my mentor and fellow contributors have been really helpful. We discussed our progress and challenges every week, which made me feel supported and encouraged.</p><p>This summer, despite the hard work and challenges, has been an incredible learning experience. I’ve been able to balance technical growth with practical application. It’s been quite an adventure, and I’m grateful for the opportunity to be a part of this journey.</p><h3><strong>Conclusion</strong></h3><p>In wrapping up, this summer has been an amazing journey of learning and growth that I’ll always treasure. A big thank you goes out to the Summer of Bitcoin program for giving me this incredible chance.</p><p>Exploring the world of Bitcoin, teaming up with fellow contributors, and learning from my mentor, Sergi, has truly changed me for the better.</p><p>To everyone who helped me along the way — whether with advice, feedback, or just words of support — thank you. Your contributions shaped my understanding, boosted my skills, and made this journey a real collaboration.</p><p>To those who are starting out, here’s a message: Believe in yourself and your abilities. The journey might get tough, but with determination and never giving up, you can overcome anything. Don’t let setbacks bring you down; they’re just steps to success. Keep going, keep learning, and don’t quit halfway. Your journey is yours, and your dedication is what really counts.</p><p>To all future contributors, I wish you an amazing journey ahead. May your experiences be as great as mine. For me, I take the lessons and memories from this summer with deep thanks and excitement for what’s next.</p><h3>Important tips</h3><h4>Selecting a language for contributing</h4><p>When you start contributing to open source, the first big decision is picking a programming language. Some folks go for what they already know, and that makes sense. But there’s also a cool option: trying something new, something not many people are working on.</p><p>I did that myself, and it can be a smart move. Why? Well, there’s less competition. If you choose a less popular language, your contributions can really stand out. It’s like taking a different path that can lead to interesting discoveries and innovations. Decision is upto you, here i am sharing tips selecting a new tech or language.</p><p><strong>Organisation Alignment:</strong> Research if there are organisations actively using the language you are interested in. Having at least 2–3 organisations utilising the language indicates its relevance and potential impact.</p><p><strong>Community Engagement:</strong> Evaluate the level of activity within the community associated with the language. A highly active community may signify a thriving ecosystem, but keep in mind that more activity could also mean increased competition. Gauge whether you prefer a bustling or moderately active community based on your comfort level and goals.</p><p><strong>Project Dynamics:</strong> Before crafting your proposal, observe ongoing discussions within the community about potential projects. This gives you insights into the existing competition and helps you make an informed decision.</p><blockquote>PS : If you believe in a particular project, focus on delivering your best work rather than worrying too much about competition. Your dedication and effort will speak volumes.</blockquote><h4>Involvement</h4><p>Actively participate in the community by interacting with others and assisting in project setups. Beyond showcasing your skills, this involvement helps maintainers get to know you. When you’re genuinely engaged, it reflects your commitment and passion, potentially giving you an edge.</p><h4>Documentation: Your Guide in Open Source</h4><p>In open source, think of documentation like the best guide. It’s not just a manual — it’s your map through the project. When you start contributing, make it a habit to read every piece of documentation available. It’s like finding answers to your questions before even asking.</p><p><em>Why It’s Important:</em> Documentation is where you learn about the project, how it works, and how to follow best practices. It’s a problem-solving toolkit — most of your issues have probably been explained there.</p><p><em>Read Every Bit:</em> Explore all the docs, from how to install to coding tips. They’re like breadcrumbs leading you through the project’s details.</p><p><em>Problem-Solving Helper:</em> Got stuck? Check the troubleshooting guide or FAQs in the documentation. Need help with a feature? Look for detailed explanations and examples.</p><h4>Project Setup: Embracing Challenges in Bitcoin Contributions</h4><p>Setting up a project for the first time in the Bitcoin world might seem tricky, but you’re not alone. If you face difficulties, ask mentors or active community members for help — it’s a learning curve for everyone.</p><p><em>Ask for Assistance:</em> Reach out for guidance; the Bitcoin community is supportive, and there’s always help available. Don’t let challenges discourage you.</p><p><em>Persist Through Challenges:</em> Persistence is key. Overcoming setup obstacles is part of the journey. Take it one step at a time, and don’t give up.</p><p><em>Community Collaboration:</em> Engage with the community. Forums and chat channels are excellent places to seek advice. Others may have tackled similar issues and can provide valuable insights.</p><p><em>Don’t Abandon Contributions:</em> If the setup feels tough, resist abandoning your contribution. View it as a chance to learn and grow. Each challenge you overcome makes you a stronger contributor.</p><p>Stay Positive: Approach setup with a positive mindset. Embrace challenges as opportunities to enhance your skills. With determination and community support, you’ll conquer the initial hurdles. 🚀💻</p><h4>Do drop a clap if you liked the blog</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f576b03ad03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>