Skip to the content.

Docs home · Overview · Architecture · Workflows

Deep Dive: Runner Engine

Overview

internal/runner is protocol-agnostic. It decides when each request starts and how many run at once, and it stops the run cleanly. It knows nothing about URLs or metrics. It only calls Requester.Do(ctx) and counts the errors that come back.

Responsibilities

Architecture

classDiagram
  class Requester {
    <<interface>>
    +Do(ctx) error
  }
  class Runner {
    -opt Options
    -plan patternPlan
    -arrival arrivalController
    +Run(ctx) Result
  }
  class arrivalController {
    <<interface>>
    +Wait(ctx) error
    +SetRate(rps float64)
  }
  class uniformArrival
  class poissonArrival
  class patternPlan {
    +rateAt(elapsed) float64, bool
  }
  class retryRequester
  class loggingRequester
  Runner --> arrivalController
  Runner --> patternPlan
  Runner --> Requester
  arrivalController <|.. uniformArrival
  arrivalController <|.. poissonArrival
  Requester <|.. retryRequester
  Requester <|.. loggingRequester
  retryRequester --> Requester : inner
  loggingRequester --> Requester : inner

Key Files

Implementation Details

Options and defaults

Options{Concurrency, TotalRequests, Duration, RatePerSecond, GracefulShutdown, Requester, LimiterFactory, LoadPatterns, ArrivalModel, RandomSeed, PoissonSampler}.

normalize() applies these defaults:

Field Default
Concurrency At least 1
GracefulShutdown 0 becomes 5 s; a negative value means cancel immediately
Limiter rate.NewLimiter(rps, max(1, rps/100)), a burst of about 10 ms; 0 rps means rate.Inf
RandomSeed 0 becomes time.Now().UnixNano()

Scheduler and workers

Run builds two contexts:

The scheduler goroutine loops:

  1. arrival.Wait(schedulerCtx).
  2. Atomically increment total.
  3. Send a permit to permits, a chan struct{} buffered to Concurrency.

The loop stops when schedulerCtx ends, when total >= TotalRequests (if TotalRequests > 0), or when Wait returns an error.

Each worker loops for range permits. It wraps its context with variables.NewContext(runCtx, variables.NewStore()), which gives every worker its own chaining store. Then it calls Requester.Do and counts errors atomically.

When scheduling finishes, permits is closed. Run then waits for the workers for up to GracefulShutdown and calls runCancel() after that. If the parent context was cancelled, it just waits for the workers.

Result{Total, Errors, Duration} counts one entry per permit. Retries are not counted.

Load patterns

The pattern types are constant, ramp, step and spike. compilePatternPlan converts them into ordered patternSegment{start, duration, fromRate, toRate} values and drops segments with zero duration. A spike compiles to a constant segment.

rateAt(elapsed) interpolates ramps linearly. It clamps every rate to at least 1 rps (minPatternRate), and returns false once the last segment has ended.

runPatternController calls arrival.SetRate(rateAt(...)) every 100 ms. When the plan is exhausted it cancels the pattern context, and scheduling stops. If both duration and patterns are set, whichever finishes first ends the run.

Arrival models

Retry and logging decorators

WithRetry(req, RetryPolicy{MaxAttempts, Delay, ShouldRetry, DelayFunc}) returns req unchanged when MaxAttempts <= 1. The loop aborts as soon as the context is cancelled.

The CLI policy (newRetryPolicy) works as follows:

Setting Value
MaxAttempts retries + 1
Not retried context.Canceled, context.DeadlineExceeded, and any HTTPError with a 4xx status other than 429
Retried HTTP 429 and 5xx, plus network and request-build errors. Request timeouts are not retried: net/http timeout errors match context.DeadlineExceeded
Backoff 100ms * 2^(attempt-1), capped at 5 s, plus jitter in [0, backoff/2)

WithLogging calls FailureLogger.LogFailure(err) for every failed attempt. The CLI’s logger writes to stderr.

Dependencies

API/Interface

type Requester interface{ Do(ctx context.Context) error }
func New(opt Options) *Runner
func (r *Runner) Run(ctx context.Context) Result
func WithRetry(req Requester, p RetryPolicy) Requester
func WithLogging(req Requester, l FailureLogger) Requester
type HTTPError struct{ StatusCode int; Body string }

Testing

Known Issues & Improvement Opportunities