Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Load Testing Implementation in Go

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Load Testing runs in O(n) time and O(n) space, in Go as in every other language.
  • ✓time.Now returns a Time carrying a monotonic reading, and time.Since uses it automatically -- subtracting two time.Now values is correct here, unlike most languages, but only if neither passed through a serialisation that strips the monotonic part.
  • ✓A reviewer insists on a custom http.Transport with MaxIdleConnsPerHost raised, since the default silently caps concurrency.
  • ✓The Go trap: The classic Go trap bites here in a specific way: a helper returning a concrete error type as an error interface makes err != nil true even when the concrete pointer is nil, so a run reports 100 percent failures against a healthy server.
  • ✓A goroutine starts at about 2 KB of stack and grows by copying, so 100k in-flight requests is a few hundred megabytes and entirely practical -- Go generators scale further per process than most of the eight.

What Load Testing actually is

Load testing drives a system at a target ARRIVAL RATE and measures the tail of the response-time distribution. The constraint that makes it hard is coordinated omission: if your generator waits for response N before sending request N+1, a stall suppresses the requests that would have been slow, and the histogram silently omits exactly the latencies you were hunting. A closed model (fixed virtual users, each looping) self-throttles this way and measures concurrency, not throughput; an open model (requests injected on a schedule regardless of completions) measures what a real arrival process does, and requires the generator to hold a queue of in-flight work. Percentiles must be recorded, not averaged: p99 of merged averages is meaningless, so record into a log-bucketed histogram. The eight languages diverge because the generator is itself a concurrent program at the machine's limits: how cheaply the runtime holds 50k in-flight requests, whether the scheduler is preemptive, whether the timing clock is monotonic, and whether GC or allocator pauses appear in your own measurements as if they were server latency.

Load Testing in Go: what you actually reach for

time.Now returns a Time carrying a monotonic reading, and time.Since uses it automatically -- subtracting two time.Now values is correct here, unlike most languages, but only if neither passed through a serialisation that strips the monotonic part. time.NewTicker paces an open model. net/http's Transport is the client, and you must set MaxIdleConnsPerHost yourself: the default of 2 makes every generator connection-starved and produces a fake latency wall. golang.org/x/time/rate gives a proper token-bucket Limiter. The stdlib has no histogram; HdrHistogram-Go is the standard port.

Go implementation

A reviewer insists on a custom http.Transport with MaxIdleConnsPerHost raised, since the default silently caps concurrency. They insist every response body is drained with io.Copy(io.Discard, resp.Body) and closed with defer, because an undrained body prevents connection reuse. Errors are returned and counted per class, never discarded with _. They reject a shared histogram guarded by a Mutex on the hot path in favour of per-goroutine histograms merged at the end.
go
package loadgen

import (
	"io"
	"net/http"
	"sync"
	"time"

	hdr "github.com/HdrHistogram/hdrhistogram-go"
)

func OpenModel(url string, rateHz, total, workers int) *hdr.Histogram {
	// Default MaxIdleConnsPerHost is 2: a fake latency wall.
	tr := &http.Transport{MaxIdleConns: 4096, MaxIdleConnsPerHost: 4096}
	client := &http.Client{Transport: tr, Timeout: 30 * time.Second}

	interval := time.Second / time.Duration(rateHz)
	due := make(chan time.Time, total) // a backlog must not stall the pacer

	locals := make([]*hdr.Histogram, workers)
	var wg sync.WaitGroup
	for w := 0; w < workers; w++ {
		h := hdr.New(1, 60_000_000, 3) // 1us..60s, 3 sig figs
		locals[w] = h
		wg.Add(1)
		go func(h *hdr.Histogram) { // per-goroutine: no mutex on the hot path
			defer wg.Done()
			for scheduled := range due {
				hit(client, url, h, scheduled)
			}
		}(h)
	}

	tick := time.NewTicker(interval)
	defer tick.Stop()
	t0 := time.Now() // monotonic reading; time.Since uses it
	for i := 0; i < total; i++ {
		<-tick.C
		due <- t0.Add(time.Duration(i) * interval) // never awaited: open model
	}
	close(due)
	wg.Wait()

	agg := hdr.New(1, 60_000_000, 3)
	for _, h := range locals {
		agg.Merge(h) // once, after every writer stopped
	}
	return agg
}

func hit(c *http.Client, url string, h *hdr.Histogram, scheduled time.Time) {
	resp, err := c.Get(url)
	if err != nil {
		return
	}
	defer resp.Body.Close() // own function, so this is per request
	io.Copy(io.Discard, resp.Body) // drain THEN close, or no reuse
	h.RecordValue(time.Since(scheduled).Microseconds()) // from SCHEDULED start
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Go-specific trap

The classic Go trap bites here in a specific way: a helper returning a concrete error type as an error interface makes err != nil true even when the concrete pointer is nil, so a run reports 100 percent failures against a healthy server. Return the error interface, not *MyErr. Second, defer resp.Body.Close() inside a loop in one long-lived goroutine defers every close to function exit and exhausts file descriptors mid-run; put the request in its own function. Third, since Go 1.14 the scheduler is asynchronously preemptive, so a tight CPU loop no longer wedges a P -- but blocking syscalls still consume an OS thread, and GOMAXPROCS threads all busy means your ticker fires late and you record it as server latency.

Performance in Go, beyond the O(n)

A goroutine starts at about 2 KB of stack and grows by copying, so 100k in-flight requests is a few hundred megabytes and entirely practical -- Go generators scale further per process than most of the eight. The concurrent mark-and-sweep collector keeps stop-the-world pauses in the sub-millisecond range, so GC contributes little to p99 but non-zero to p99.9; set GOGC higher to trade memory for fewer cycles during the measurement window. Escape analysis keeps small request structs on the stack; sync.Pool for response buffers cuts allocation. Every interface method call is an indirect dispatch through the itab. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Load Testing between languages.

Real-World Applications

Load Testing applies wherever its problem shape appears in your own code. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Load Testing helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Load Testing appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Load Testing over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Load Testing to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Load Testing?

time.Now returns a Time carrying a monotonic reading, and time.Since uses it automatically -- subtracting two time.Now values is correct here, unlike most languages, but only if neither passed through a serialisation that strips the monotonic part. time.NewTicker paces an open model. net/http's Transport is the client, and you must set MaxIdleConnsPerHost yourself: the default of 2 makes every generator connection-starved and produces a fake latency wall. golang.org/x/time/rate gives a proper token-bucket Limiter. The stdlib has no histogram; HdrHistogram-Go is the standard port.

What is the most common Go mistake when implementing Load Testing?

The classic Go trap bites here in a specific way: a helper returning a concrete error type as an error interface makes err != nil true even when the concrete pointer is nil, so a run reports 100 percent failures against a healthy server. Return the error interface, not *MyErr. Second, defer resp.Body.Close() inside a loop in one long-lived goroutine defers every close to function exit and exhausts file descriptors mid-run; put the request in its own function. Third, since Go 1.14 the scheduler is asynchronously preemptive, so a tight CPU loop no longer wedges a P -- but blocking syscalls still consume an OS thread, and GOMAXPROCS threads all busy means your ticker fires late and you record it as server latency.

How does Load Testing actually perform in Go?

A goroutine starts at about 2 KB of stack and grows by copying, so 100k in-flight requests is a few hundred megabytes and entirely practical -- Go generators scale further per process than most of the eight. The concurrent mark-and-sweep collector keeps stop-the-world pauses in the sub-millisecond range, so GC contributes little to p99 but non-zero to p99.9; set GOGC higher to trade memory for fewer cycles during the measurement window. Escape analysis keeps small request structs on the stack; sync.Pool for response buffers cuts allocation. Every interface method call is an indirect dispatch through the itab. Time complexity is O(n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Devin offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.