Using Vegeta as a Go Library for Custom Load Tests

Using Vegeta as a Go Library for Custom Load Tests

The Vegeta CLI handles most load testing scenarios, but when you need dynamic request bodies, stateful sequences, or load tests embedded in your Go test suite, the library gives you full control. You import vegeta/lib, build an Attacker, feed it a Targeter function, and collect Metrics -- all in plain Go code.

Adding the Dependency

go get github.com/tsenart/vegeta/v12

Import in your code:

import vegeta "github.com/tsenart/vegeta/v12/lib"

Basic Attack with Static Target

The simplest library usage mirrors the CLI:

package main

import (
    "fmt"
    "time"

    vegeta "github.com/tsenart/vegeta/v12/lib"
)

func main() {
    rate := vegeta.Rate{Freq: 100, Per: time.Second}
    duration := 30 * time.Second
    target := vegeta.Target{
        Method: "GET",
        URL:    "https://api.example.com/health",
    }

    targeter := vegeta.NewStaticTargeter(target)
    attacker := vegeta.NewAttacker()

    var metrics vegeta.Metrics
    for res := range attacker.Attack(targeter, rate, duration, "health-check") {
        metrics.Add(res)
    }
    metrics.Close()

    fmt.Printf("Requests: %d\n", metrics.Requests)
    fmt.Printf("Success:  %.2f%%\n", metrics.Success*100)
    fmt.Printf("P50:      %s\n", metrics.Latencies.P50)
    fmt.Printf("P99:      %s\n", metrics.Latencies.P99)
    fmt.Printf("Max:      %s\n", metrics.Latencies.Max)
}

attacker.Attack returns a <-chan *Result channel. The for-range loop receives results as they come in. metrics.Add accumulates them. metrics.Close() must be called before reading percentiles -- it finalizes internal state.

Adding Headers

import "net/http"

target := vegeta.Target{
    Method: "GET",
    URL:    "https://api.example.com/users",
    Header: http.Header{
        "Authorization": []string{"Bearer " + authToken},
        "Accept":        []string{"application/json"},
        "X-Request-ID": []string{"load-test-001"},
    },
}

POST with a JSON Body

import (
    "bytes"
    "encoding/json"
    "net/http"
)

type OrderRequest struct {
    ProductID string `json:"product_id"`
    Quantity  int    `json:"quantity"`
}

body, _ := json.Marshal(OrderRequest{
    ProductID: "prod_abc123",
    Quantity:  1,
})

target := vegeta.Target{
    Method: "POST",
    URL:    "https://api.example.com/orders",
    Header: http.Header{
        "Content-Type":  []string{"application/json"},
        "Authorization": []string{"Bearer " + authToken},
    },
    Body: body,
}

Custom Targeter Functions

vegeta.NewStaticTargeter always sends the same request. For dynamic requests, implement vegeta.Targeter:

type Targeter func(*Target) error

A custom targeter that randomizes user IDs:

import (
    "fmt"
    "math/rand"
    "net/http"
)

func randomUserTargeter(userIDs []string, token string) vegeta.Targeter {
    return func(t *vegeta.Target) error {
        id := userIDs[rand.Intn(len(userIDs))]
        t.Method = "GET"
        t.URL = fmt.Sprintf("https://api.example.com/users/%s", id)
        t.Header = http.Header{
            "Authorization": []string{"Bearer " + token},
        }
        return nil
    }
}

Use it:

ids := []string{"usr_001", "usr_002", "usr_003", "usr_004", "usr_005"}
targeter := randomUserTargeter(ids, authToken)

attacker := vegeta.NewAttacker()
var metrics vegeta.Metrics

for res := range attacker.Attack(targeter, rate, duration, "random-users") {
    metrics.Add(res)
}
metrics.Close()

Rotating Targets with Multiple Endpoints

Simulate a realistic traffic mix by rotating through endpoint types:

import (
    "encoding/json"
    "fmt"
    "net/http"
    "sync/atomic"
)

func mixedTargeter(token string) vegeta.Targeter {
    var counter uint64

    return func(t *vegeta.Target) error {
        n := atomic.AddUint64(&counter, 1)
        t.Header = http.Header{
            "Authorization": []string{"Bearer " + token},
            "Accept":        []string{"application/json"},
        }

        switch n % 10 {
        case 0, 1, 2, 3: // 40% - product list
            t.Method = "GET"
            t.URL = fmt.Sprintf("https://api.example.com/products?page=%d", (n%5)+1)

        case 4, 5, 6: // 30% - product detail
            ids := []string{"prod_001", "prod_002", "prod_003"}
            t.Method = "GET"
            t.URL = "https://api.example.com/products/" + ids[n%3]

        case 7, 8: // 20% - search
            queries := []string{"laptop", "phone", "tablet"}
            t.Method = "GET"
            t.URL = fmt.Sprintf("https://api.example.com/search?q=%s", queries[n%3])

        case 9: // 10% - cart add
            body, _ := json.Marshal(map[string]interface{}{
                "product_id": "prod_001",
                "quantity":   1,
            })
            t.Method = "POST"
            t.URL = "https://api.example.com/cart/items"
            t.Header["Content-Type"] = []string{"application/json"}
            t.Body = body
        }

        return nil
    }
}

Configuring the Attacker

vegeta.NewAttacker accepts functional options:

attacker := vegeta.NewAttacker(
    vegeta.Timeout(2*time.Second),          // per-request timeout
    vegeta.Workers(50),                      // goroutine count
    vegeta.MaxConnections(100),              // max open TCP connections
    vegeta.KeepAlive(true),                  // reuse connections
    vegeta.H2C(false),                       // disable HTTP/2 cleartext
    vegeta.TLSConfig(tlsCfg),               // custom TLS config
)

For high throughput (>1000 RPS), increase workers:

attacker := vegeta.NewAttacker(
    vegeta.Workers(200),
    vegeta.MaxConnections(500),
)

Threshold-Based Assertions in Go Tests

The library integrates naturally with testing.T:

package load_test

import (
    "net/http"
    "testing"
    "time"

    vegeta "github.com/tsenart/vegeta/v12/lib"
)

func TestAPIUnderLoad(t *testing.T) {
    if testing.Short() {
        t.Skip("skipping load test in short mode")
    }

    rate := vegeta.Rate{Freq: 200, Per: time.Second}
    duration := 30 * time.Second

    targeter := vegeta.NewStaticTargeter(vegeta.Target{
        Method: "GET",
        URL:    "http://localhost:8080/api/health",
        Header: http.Header{
            "Accept": []string{"application/json"},
        },
    })

    attacker := vegeta.NewAttacker(
        vegeta.Timeout(2*time.Second),
    )

    var metrics vegeta.Metrics
    for res := range attacker.Attack(targeter, rate, duration, "health-load") {
        metrics.Add(res)
    }
    metrics.Close()

    t.Logf("Requests: %d", metrics.Requests)
    t.Logf("Success:  %.2f%%", metrics.Success*100)
    t.Logf("P50:      %s", metrics.Latencies.P50)
    t.Logf("P99:      %s", metrics.Latencies.P99)

    if metrics.Success < 0.995 {
        t.Errorf("success rate %.2f%% below 99.5%% threshold", metrics.Success*100)
    }

    maxP99 := 100 * time.Millisecond
    if metrics.Latencies.P99 > maxP99 {
        t.Errorf("P99 %s exceeds %s threshold", metrics.Latencies.P99, maxP99)
    }

    if metrics.Throughput < 195 {
        t.Errorf("throughput %.1f RPS below 195 RPS minimum", metrics.Throughput)
    }
}

Run with:

go test ./load_test/... -v -run TestAPIUnderLoad
# or skip during unit tests:
go test ./... -short

Collecting Results Per Request

For per-request analysis, collect results into a slice instead of aggregating immediately:

var results []*vegeta.Result

for res := range attacker.Attack(targeter, rate, duration, "detailed") {
    results = append(results, res)
    // inspect as they come in
    if res.Code >= 500 {
        fmt.Printf("Error at %s: status %d, latency %s\n",
            res.Timestamp.Format(time.RFC3339),
            res.Code,
            res.Latency,
        )
    }
}

// Build metrics from collected results
var metrics vegeta.Metrics
for _, r := range results {
    metrics.Add(r)
}
metrics.Close()

Encoding Results to a File

To save results from library code for later CLI analysis:

import (
    "os"
    vegeta "github.com/tsenart/vegeta/v12/lib"
)

f, err := os.Create("results.bin")
if err != nil {
    panic(err)
}
defer f.Close()

enc := vegeta.NewEncoder(f)

for res := range attacker.Attack(targeter, rate, duration, "save-results") {
    if err := enc.Encode(res); err != nil {
        panic(err)
    }
}

Then analyze from the CLI:

vegeta report < results.bin
vegeta report -type=hist[0,10ms,50ms,100ms,500ms] < results.bin

Stopping Early on Threshold Breach

Use a goroutine to monitor metrics and stop the attack if things go wrong:

attacker := vegeta.NewAttacker()
results := attacker.Attack(targeter, rate, duration, "monitored")

var metrics vegeta.Metrics
for res := range results {
    metrics.Add(res)

    // stop if success drops below 95% after the first 500 requests
    if metrics.Requests > 500 && metrics.Success < 0.95 {
        attacker.Stop()
        break
    }
}
metrics.Close()

attacker.Stop() drains the channel and allows the for-range to exit cleanly.

The Go library is most valuable when your load test logic can't be expressed as a static target file -- when tokens rotate, when request bodies depend on prior responses, or when you want load tests to live alongside unit tests in the same go test run.

Read more

Start now free