Home Backend Development Golang Adding API Rate Limiting to Your Go API

Adding API Rate Limiting to Your Go API

Oct 07, 2024 am 10:49 AM

Adding API Rate Limiting to Your Go API

Alright, folks, we’ve covered a lot so far: JWT authentication, database connections, logging, and error handling. But what happens when your API starts getting slammed with requests? Without control, high traffic can lead to slow response times or even downtime. ?

This week, we’re going to solve that by implementing rate limiting to control the flow of traffic. We’ll be using the simple and effective golang.org/x/time/rate package. Later, when my own ThrottleX solution is ready, I’ll show you how to integrate that as a more scalable option. (Psst, check out my GitHub at github.com/neelp03/throttlex for updates! Feel free to comment any issues you see in there o7)

Why Rate Limiting? ?

Rate limiting is like a bouncer for your API—it controls the number of requests users can make within a given timeframe. This prevents your API from getting overwhelmed, ensuring smooth and fair access for all users. Rate limiting is essential for:

  • Preventing Abuse: Stops bad actors or overly enthusiastic users from overwhelming your API.
  • Stability: Keeps your API responsive and reliable, even during traffic spikes.
  • Fairness: Allows resources to be shared equally among users.

Step 1: Installing the time/rate Package

The golang.org/x/time/rate package is part of the extended Go libraries and provides a straightforward token-based rate limiter. To get started, you’ll need to install it:


go get golang.org/x/time/rate


Copy after login

Step 2: Setting Up the Rate Limiter

Let’s create a rate-limiting middleware that controls the number of requests a client can make. In this example, we’ll limit clients to 5 requests per minute.


package main

import (
    "net/http"
    "golang.org/x/time/rate"
    "sync"
    "time"
)

// Create a struct to hold each client's rate limiter
type Client struct {
    limiter *rate.Limiter
}

// In-memory storage for clients
var clients = make(map[string]*Client)
var mu sync.Mutex

// Get a client's rate limiter or create one if it doesn't exist
func getClientLimiter(ip string) *rate.Limiter {
    mu.Lock()
    defer mu.Unlock()

    // If the client already exists, return the existing limiter
    if client, exists := clients[ip]; exists {
        return client.limiter
    }

    // Create a new limiter with 5 requests per minute
    limiter := rate.NewLimiter(5, 1)
    clients[ip] = &Client{limiter: limiter}
    return limiter
}


Copy after login

Step 3: Creating the Rate Limiting Middleware

Now, let’s use the getClientLimiter function in a middleware that will restrict access based on the rate limit.


func rateLimitingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ip := r.RemoteAddr
        limiter := getClientLimiter(ip)

        // Check if the request is allowed
        if !limiter.Allow() {
            http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
            return
        }

        next.ServeHTTP(w, r)
    })
}


Copy after login

How It Works:

  1. IP-Based Limiting: Each client is identified by their IP address. We check the client’s IP and assign a rate limiter to it.
  2. Request Check: The limiter.Allow() method checks if the client is within the rate limit. If they are, the request proceeds to the next handler; if not, we respond with 429 Too Many Requests.

Step 4: Applying the Middleware Globally ?

Now let’s hook up our rate limiter to the API so every request has to pass through it:


func main() {
    db = connectDB()
    defer db.Close()

    r := mux.NewRouter()

    // Apply rate-limiting middleware globally
    r.Use(rateLimitingMiddleware)

    // Other middlewares
    r.Use(loggingMiddleware)
    r.Use(errorHandlingMiddleware)

    r.HandleFunc("/login", login).Methods("POST")
    r.Handle("/books", authenticate(http.HandlerFunc(getBooks))).Methods("GET")
    r.Handle("/books", authenticate(http.HandlerFunc(createBook))).Methods("POST")

    fmt.Println("Server started on port :8000")
    log.Fatal(http.ListenAndServe(":8000", r))
}


Copy after login

By applying r.Use(rateLimitingMiddleware), we ensure that every incoming request is checked by the rate limiter before it reaches any endpoint.


Step 5: Testing the Rate Limiting ?

Start your server:


go run main.go


Copy after login

Now, let’s hit the API with some requests. You can use a loop with curl to simulate multiple requests in a row:


for i in {1..10}; do curl http://localhost:8000/books; done


Copy after login

Since we set the limit to 5 requests per minute, you should see 429 Too Many Requests responses once you exceed the allowed rate.


What’s Next?

And there you have it—rate limiting with golang.org/x/time/rate to keep your API stable and responsive under pressure. Rate limiting is a crucial tool for any scalable API, and we’re just scratching the surface here.

Once ThrottleX is production-ready, I’ll be posting a follow-up tutorial to show you how to integrate it into your Go API for even more flexibility and distributed rate limiting. Keep an eye on my ThrottleX GitHub repo for updates!

Next week, we’re going to containerize our API with Docker, so it’s ready to run anywhere. Stay tuned, and happy coding! ??

The above is the detailed content of Adding API Rate Limiting to Your Go API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Getting Started with Go: A Beginner's Guide Getting Started with Go: A Beginner's Guide Apr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. Python: The Pros and Cons Golang vs. Python: The Pros and Cons Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

See all articles