i built a distributed rate limiter in go with zero go experience

lagos

I'd been hearing about Go for a while. Fast, concurrent, simple. But every time I tried to get into it, the tutorials felt written for people who already knew Go. Concepts were thrown at you before you understood why they existed.

So I decided to learn differently. Instead of following a tutorial, I picked a real project and built it from scratch.

The project chose itself after I found a post on the Uber Engineering blog: From Static Rate Limiting to Intelligent Load Management. It walks through how Uber's team built overload protection for databases handling tens of millions of requests per second.

What caught me wasn't the final system. It was why their first approach failed. They started with a simple Redis-based quota system. Every request hit Redis, quotas were set statically, and the cost model was too rough to reflect real load. It collapsed under real production traffic.

Their takeaway stuck with me: overload management must live as close to the storage nodes as possible, and static configurations will always fight a losing battle against a dynamic system.

I wasn't going to build Uber's system. But I wanted to understand the foundation: what a rate limiter actually is before it becomes intelligent, distributed and priority-aware. So I built one. A distributed rate limiter with a sliding window, in a language I'd never written. No Go experience, just a TypeScript background and a problem worth understanding from the ground up.

This is everything I learned.

Why a Rate Limiter?

A rate limiter sounds simple until you build one. At its core it answers one question: has this user made too many requests recently?

But the moment you think about it seriously, the questions pile up. What happens when several requests arrive in the same millisecond? If you run ten servers, does each one keep its own count, or do they share it? If you track every user who ever made a request, does that list grow forever?

These aren't theoretical problems. They're exactly the problems that push you into Go's most important ideas: concurrency, shared state, goroutines, and distributed systems.

The Mental Shift From TypeScript

Before a single line of Go, the biggest adjustment isn't the syntax. It's the way of thinking.

TypeScript runs on one thread. async/await gives you the illusion of concurrency. Under the hood, only one thing runs at a time, and the event loop manages it for you. You rarely have to think about two pieces of code touching the same data at once.

Go is genuinely concurrent. Goroutines really do run at the same time. So you have to think about what happens when two requests hit the same function in the same millisecond. Ignore it and things break in ways that are hard to reproduce and harder to debug.

There's no try/catch. In TypeScript, if you don't wrap something, errors bubble up quietly. In Go, every function that can fail returns two values, the result and an error:

result, err := doSomething()
if err != nil {
    // you have to deal with this
}

It feels wordy at first. After a while you realise it's better: every failure path is visible in the code, and you can't accidentally ignore one.

There are no classes. Go splits the class into a struct (the data) and methods (the behaviour, attached separately). This is the real struct from the project:

type RateLimiter struct {
    mu       sync.Mutex
    requests []time.Time   // timestamps in the current window
    limit    int           // max requests allowed
    window   time.Duration // how long the window is
}

func (r *RateLimiter) Allow() bool { … }

The (r *RateLimiter) before the function name is Go saying "this function belongs to RateLimiter." r is like this in TypeScript, except you name it yourself.

Stage 1: The Sliding Window

For every request, look back one window and count how many requests happened in that time. Under the limit? Allow it and record the timestamp. Over? Reject it.

The window slides with every request. A fixed window is different: everyone's count resets at the same moment on the clock. That has a nasty edge case. A client can send a full limit just before the reset and another full limit just after, doubling the allowed rate in a short burst. A sliding window doesn't fall for it.

A limit of 100 a minute, with 100 requests at 0:59 and 100 more at 1:00. A fixed window allows all 200, because the second 100 land in a new window. A sliding window looks back one minute from 1:00, still sees the first 100, and rejects the second 100.

The implementation is a struct holding a slice of timestamps, a Mutex protecting it, and an Allow() method:

func (r *RateLimiter) Allow() bool {
    r.mu.Lock()
    defer r.mu.Unlock()

    now := time.Now()
    windowStart := now.Add(-r.window)

    // keep only the timestamps inside the window
    var valid []time.Time
    for _, t := range r.requests {
        if t.After(windowStart) {
            valid = append(valid, t)
        }
    }
    r.requests = valid

    if len(r.requests) >= r.limit {
        return false
    }

    r.requests = append(r.requests, now)
    return true
}

Two Go things are worth understanding in this block.

defer r.mu.Unlock(). defer schedules a call to run when the surrounding function returns, however it returns. So even when Allow() returns false early, the mutex is always unlocked. This is Go's standard pattern: lock, immediately defer the unlock, then do your work. You never forget to unlock.

The Mutex itself. Without it, two requests could read the count at the same time, both think they're under the limit, and both get through when only one should. The mutex lets one goroutine through that block at a time, like a single-occupancy door.

It holds up. A test that fires 1,000 goroutines at the same key at once, with a limit of 5, lets exactly 5 through. Five runs, five times out of five.

Stage 2: Multiple Users

A single limiter has an obvious problem: one global limit for everyone. If alice hits her limit, bob is blocked too.

The fix is a map with one *RateLimiter per key: per IP, per user, per whatever makes sense for your app.

type MultiLimiter struct {
    mu       sync.RWMutex
    limiters map[string]*RateLimiter
    lastSeen map[string]time.Time // when each key was last used
    done     chan struct{}         // the stop signal
    limit    int
    window   time.Duration
}

Notice sync.RWMutex instead of sync.Mutex. This is the first real concurrency nuance. Think of a library reading room. Many people can read at once without disturbing each other. But when someone needs to rearrange the shelves, everyone has to wait.

  • Reading: many goroutines can read the map at the same time (RLock).
  • Writing: only one goroutine can write, and only when nobody is reading (Lock).

In this project, Allow() takes the full write lock, because it may add a new key and it always updates when the key was last seen. The read lock is for reading only, like counting the keys.

Stage 3: Goroutines and Channels

The MultiLimiter now leaks memory. Every key stays in the map forever, even if that user hasn't made a request in hours. In a real app with thousands of users, that adds up.

The fix is a background goroutine that sweeps idle keys out on a timer. This is where Go's concurrency starts to feel genuinely different.

func (m *MultiLimiter) StartCleanup(interval, maxIdle time.Duration) {
    ticker := time.NewTicker(interval)

    go func() {
        for {
            select {
            case <-ticker.C:
                m.cleanup(maxIdle)
            case <-m.done:
                ticker.Stop()
                return // exits the goroutine
            }
        }
    }()
}

Three things are happening here.

go func() { … }() starts an anonymous goroutine. The function is defined and immediately runs in the background. StartCleanup returns straight away while the goroutine keeps going.

time.Ticker sends the current time into a channel at a regular interval. ticker.C is that channel.

select listens to several channels at once and runs whichever is ready first. If the ticker fires, clean up. If the done channel closes (someone called Stop()), exit.

The done channel is a common Go pattern for telling goroutines to stop:

done: make(chan struct{})

// somewhere else:
close(done) // tells everyone listening

chan struct{} carries no data at all. It's just a signal.

In the server, the sweep runs every minute and drops any key that's been idle for five. Fill the limiter with 10,000 different IPs, and one sweep after they go quiet, the map is back to 0 keys.

This was the moment Go's concurrency clicked for me. In TypeScript, the runtime manages concurrency for you. In Go, you write the goroutines. You write the channels. You decide when things run and when they stop. More responsibility, and much more control.

Stage 4: HTTP Middleware

Go's standard library includes a production-grade HTTP server. No Express, no Fastify, no framework needed.

The whole HTTP system is built around one interface:

type Handler interface {
    ServeHTTP(w http.ResponseWriter, r *http.Request)
}

If your type has a ServeHTTP method with that signature, it's a valid HTTP handler. There's no implements keyword. Go works it out by itself. That's what makes Go interfaces powerful: they're satisfied without being declared.

Middleware follows naturally. It's a handler that wraps another handler:

type Limiter interface {
    Allow(key string) bool
}

func Middleware(l Limiter, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ip, _, err := net.SplitHostPort(r.RemoteAddr)
        if err != nil {
            ip = r.RemoteAddr
        }

        if !l.Allow(ip) {
            w.WriteHeader(http.StatusTooManyRequests)
            fmt.Fprintln(w, "rate limit exceeded, slow down")
            return // the request stops here
        }

        next.ServeHTTP(w, r)
    })
}

Notice the Limiter interface as the first parameter. Both MultiLimiter and the RedisLimiter coming next have the same Allow(key string) bool method, so both satisfy it. The middleware doesn't know or care which one it's talking to.

The middleware also holds a real bug I hit. r.RemoteAddr is "IP:PORT", not just the IP. Every curl request opens a new connection on a new port, so the limiter saw every request as a different user, and nobody ever hit the limit. net.SplitHostPort strips the port.

You can see the difference plainly. Send 10 requests from one IP, each on a new port, with a limit of 5. With the port left in the key, all 10 get through, spread across 10 keys. With the port stripped, 5 get through, all on 1 key.

Stage 5: Making It Actually Distributed

Here's the problem with everything so far: the state lives in one server's memory. In production you run several instances behind a load balancer, and each has its own map. Alice can send five requests to instance A and five to instance B, and neither knows about the other. The rate limiter is useless.

The fix is Redis. Move the state out of any one server into a shared store every instance can read and write.

The data structure is a Redis sorted set. Every member has a score, and Redis can quickly find and delete every member with a score in a range. Each request is stored with its timestamp in milliseconds as the score, and the timestamp in nanoseconds as the member, so two requests in the same millisecond don't overwrite each other:

Key: "rate:192.168.1.1"
member (nanoseconds)   score (milliseconds)
────────────────────   ────────────────────
1719000001000123000 →  1719000001000
1719000001200456000 →  1719000001200
1719000001800789000 →  1719000001800

To check the window: remove everything scored older than now minus the window, count what's left, compare it to the limit.

But done from Go, that's three separate Redis calls:

  1. remove old entries
  2. count what's left
  3. if under the limit, add the new entry

There's a gap between steps 2 and 3. Two requests arrive together and both count 4, under a limit of 5. Both think they can go through. Both add themselves. The count becomes 6, and the limit is broken.

Three separate calls from Go on the left, with a gap between counting and adding where another request also reads 4. On the right, the same three steps inside one Lua script, which Redis runs as one step.

The solution is a Lua script. Redis runs a Lua script atomically: the whole script is one step that nothing else can interrupt. Nothing can run between the count and the add. This is the script from the project:

local key      = KEYS[1]
local now_ms   = tonumber(ARGV[1])
local now_ns   = ARGV[2]
local window   = tonumber(ARGV[3])
local limit    = tonumber(ARGV[4])

redis.call('ZREMRANGEBYSCORE', key, 0, now_ms - window)

local count = redis.call('ZCARD', key)

if count < limit then
    redis.call('ZADD', key, now_ms, now_ns)
    redis.call('PEXPIRE', key, window)
    return 1
end

return 0

PEXPIRE deletes the whole key one window after the last allowed request, so Redis cleans up after itself.

How much does the gap matter? Against a local Redis, send 200 requests at once to one key with a limit of 5, five runs each. The three-call version let through 11, 21, 12, 65 and 79. The Lua script let through 5, every time.

Requests let through out of 200 sent at once with a limit of 5, five runs each. Three separate calls let through 11, 12, 21, 65 and 79. The Lua script let through 5 in all five runs.

And in Go:

func (r *RedisLimiter) Allow(key string) bool {
    ctx := context.Background()

    nowMs := time.Now().UnixMilli() // the score
    nowNs := time.Now().UnixNano()  // the unique member
    windowMs := r.window.Milliseconds()

    result, err := r.script.Run(ctx, r.client, []string{key}, nowMs, nowNs, windowMs, r.limit).Int()
    if err != nil {
        fmt.Println("Redis error:", err)
        return true
    }

    return result == 1
}

Notice return true when Redis errors. This is failing open: if Redis is unavailable, allow the request rather than rejecting everything. A Redis outage taking your whole application down with it is almost always worse than briefly not enforcing rate limits. Swap it to return false if your use case needs the opposite.

What I Actually Learned

Looking back, the rate limiter wasn't really about rate limiting. It was a vehicle for understanding Go's actual ideas.

Structs and pointer receivers. The * before a type means "a pointer to this thing, not a copy." Methods that change the struct need pointer receivers. This trips you up once before it sticks.

Mutexes. Shared state that changes, in a concurrent program, is a bug waiting to happen. A Mutex lets one goroutine into a critical section at a time. RWMutex lets reads happen together while writes take turns.

Goroutines and channels. Go's concurrency model is genuinely different. You write the threads, and you write how they talk. It's more work than an event loop, and much more powerful.

Interfaces are implicit. If your type has the right methods, it satisfies the interface. No implements. That makes it easy to swap backends without touching the caller.

Errors are values. Wordy, but explicit. Every failure path is visible.

What's Next

This project is the foundation for the second Go project in this series: a messaging system with a pub/sub broker. Everything here carries over: goroutines, channels, select, interfaces, structs. But there, channels stop being a cleanup mechanism and become the core of the design. Goroutines talk to each other through typed pipes in real time.

The full code is on GitHub: abubakar2906/rate-limiter.

And if you're a TypeScript developer thinking about learning Go, build something real. Tutorials tell you what Go can do. A project shows you why it works the way it does.

This article is part of a series on learning Go through building real systems.

older: building courseflow: bridging the gap in university academic tracking

first published on medium.

email / github / linkedin / last updated
26/11/26