Load Testing Implementation in Go
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 in Go: what you actually reach for
Go implementation
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 FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
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).
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 trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.