0Pricing
Go Academy · Lesson

golang.org/x/time/rate

Use the rate limiter.

golang.org/x/time/rate is a free Go Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The rate Package

golang.org/x/time/rate provides a production-ready token bucket Limiter. It is the standard choice for rate limiting in Go.

  • Battle-tested implementation
  • Allow, Wait, and Reserve methods
  • Context-aware

Creating a Limiter

rate.NewLimiter takes a rate (tokens per second) and a burst size. rate.Limit is a float64 of events per second.

limiter := rate.NewLimiter(rate.Limit(10), 5)

rate.Every

If you think in intervals rather than per-second rates, rate.Every converts a duration into a rate. One event every 200ms equals five per second.

limiter := rate.NewLimiter(rate.Every(200*time.Millisecond), 1)

Allow

Allow reports whether a token is available right now. It returns true and consumes a token, or returns false immediately. Use it to reject excess requests.

if !limiter.Allow() {
    fmt.Println("rejected: too many requests")
    return
}

Wait

Wait blocks until a token is available or the context is cancelled. It is ideal when you want to pace work rather than drop it.

if err := limiter.Wait(ctx); err != nil {
    return err
}
doWork()

Reserve

Reserve returns a Reservation describing how long to wait. Call Delay() to learn the wait, and Cancel() if you decide not to proceed.

r := limiter.Reserve()
if !r.OK() {
    return
}
time.Sleep(r.Delay())

Note: External Package

The rate package is not in the standard library, so it requires go get golang.org/x/time/rate and a module. Snippets that import it are illustrative and not run inline here.

A Runnable Standard-Library Analog

Since the rate package is external, here is a standard-library pacing loop that mimics Wait by ticking every 200ms.

package main

import (
    "fmt"
    "time"
)

func main() {
    tick := time.NewTicker(200 * time.Millisecond)
    defer tick.Stop()
    for i := 0; i < 4; i++ {
        <-tick.C
        fmt.Println("processed event", i)
    }
}

Tuning at Runtime

You can change limits on the fly with SetLimit and SetBurst. This is handy when a config reload or an upstream 429 response tells you to slow down.

limiter.SetLimit(rate.Limit(20))
limiter.SetBurst(10)

Per-Client Limiters

Keep a map from client key to *rate.Limiter, guarded by a mutex. Create a limiter on first request for that key, then reuse it for subsequent requests.

func getLimiter(m map[string]*rate.Limiter, key string) *rate.Limiter {
    if l, ok := m[key]; ok {
        return l
    }
    l := rate.NewLimiter(rate.Limit(5), 10)
    m[key] = l
    return l
}

HTTP Middleware

Wrap handlers so each request calls Allow() first. On false, respond with HTTP 429 Too Many Requests. This is the canonical server-side rate limit.

Quick Check

Test your rate package knowledge.

Recap

You learned golang.org/x/time/rate:

  • NewLimiter(rate, burst) creates the bucket
  • rate.Every converts an interval to a rate
  • Allow rejects, Wait paces, Reserve reports delay
  • SetLimit and SetBurst tune at runtime
  • Per-client map plus HTTP 429 for servers

Frequently asked questions

Is the “golang.org/x/time/rate” lesson free?

Yes — the full text of “golang.org/x/time/rate” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “golang.org/x/time/rate”?

Use the rate limiter. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “golang.org/x/time/rate” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Token Bucket Concept
  2. golang.org/x/time/rate
  3. Throttling Goroutines
  4. Backoff and Retry
← Back to Go Academy