Simple Rate Limiting in Go with Gin

Nova Novriansyah
NovAi-Go Programming 101
3 min readOct 31, 2024

Rate limiting helps control the number of requests a server can handle in a given time. It’s essential for managing traffic, preventing abuse, and ensuring the stability of your service. In this article, we’ll implement a basic rate limiter in Go using the Gin framework.

In this example, we’ll set up a rate limiter that:

• Allows 1 request per second.

• Has a burst capacity of 5 requests.

This means users can make up to 5 requests quickly (burst) but will be limited to 1 request per second on average.

Setting Up the Project

1. Install the Gin framework if you haven’t already:

go get -u github.com/gin-gonic/gin

2. Now, let’s implement the rate limiter using Gin.

Code Example: Rate Limiting with Middleware in Gin

The code below creates a simple rate limiter as middleware in a Gin application. This middleware checks if the request count has exceeded the limit before allowing access to the endpoint.

package main

import (
"github.com/gin-gonic/gin"
"net/http"
"time"
"golang.org/x/time/rate"
)

// Define a rate limiter with 1 request per second and a burst of 5.
var limiter = rate.NewLimiter(1, 5)

// Middleware to check the rate limit.
func rateLimiter(c *gin.Context) {
if !limiter.Allow() {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many requests"})
c.Abort()
return
}
c.Next()
}

func main() {
r := gin.Default()

// Apply the rate limiting middleware
r.Use(rateLimiter)

// Define a simple route
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Welcome to the rate-limited endpoint!")
})

// Run the server
r.Run(":8080")
}

Explanation of the Code

1. Rate Limiter Initialization:

var limiter = rate.NewLimiter(1, 5)

We use the rate.NewLimiter function from the golang.org/x/time/rate package to create a rate limiter. Here, 1 is the number of requests allowed per second, and 5 is the burst capacity, allowing a short burst of requests before limiting.

2. Rate Limiting Middleware:

func rateLimiter(c *gin.Context) {
if !limiter.Allow() {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "too many requests"})
c.Abort()
return
}
c.Next()
}

The rateLimiter function is a Gin middleware that checks if a request is allowed using limiter.Allow(). If the limit is exceeded, it returns a 429 Too Many Requests status with a JSON error message and stops further processing (c.Abort()). If the request is allowed, it calls c.Next() to proceed.

3. Applying the Middleware:

r.Use(rateLimiter)

We use r.Use(rateLimiter) to apply the rateLimiter middleware to all routes in the Gin router.

4. Simple Route:

r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Welcome to the rate-limited endpoint!")
})

We define a simple route that returns a welcome message. The rate limiting middleware will apply to this route.

5. Running the Server:

r.Run(":8080")

This starts the server on http://localhost:8080.

Testing the Rate Limiter

To test the rate limiter:

1. Run the server with go run main.go.

2. Open a browser or use a tool like curl to make multiple requests to http://localhost:8080/.

3. You should see “Welcome to the rate-limited endpoint!” for the first few requests, but if you make requests too quickly, you’ll start receiving “too many requests” responses.

In this article, we implemented a basic rate limiter in Go using the Gin framework and the rate package from Go’s standard library. This approach provides an easy way to protect your application from high traffic and abuse. Rate limiting is essential for API stability, and by applying it as middleware, we can control access to any route in our application.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

NovAi-Go Programming 101
NovAi-Go Programming 101

Published in NovAi-Go Programming 101

The place to learn, get update and enhance you golang skill

Nova Novriansyah
Nova Novriansyah

Written by Nova Novriansyah

C|CISO, CEH, CC, CVA,CertBlockchainPractitioner, Google Machine Learning , Tensorflow, Unity Cert, Arduino Cert, AWS Arch Cert. CTO, IT leaders. Platform owners

No responses yet

What are your thoughts?