Skip to content

Instantly share code, notes, and snippets.

@sedkis
Created September 17, 2025 15:52
Show Gist options
  • Select an option

  • Save sedkis/568f840d03a4f794727cda665932190c to your computer and use it in GitHub Desktop.

Select an option

Save sedkis/568f840d03a4f794727cda665932190c to your computer and use it in GitHub Desktop.
Custom Rate Limit Pattern (via Custom Plugin)

In your custom plugin -- when setting the session for a valid request, simply add the "rate_limit_pattern" key into the metadata, with the unique key that you want Tyk to track a rate limit for.

This may be one user, a collection of users, an app, etc.

package main
import (
"bytes"
"context"
"encoding/base64"
"io/ioutil"
"net/http"
"os"
"github.com/buger/jsonparser"
"github.com/TykTechnologies/tyk-pump/analytics"
"github.com/TykTechnologies/tyk/ctx"
"github.com/TykTechnologies/tyk/log"
"github.com/TykTechnologies/tyk/request"
"github.com/TykTechnologies/tyk/user"
)
var logger = log.Get()
// IP Rate Limiter
func Authenticate(rw http.ResponseWriter, r *http.Request) {
requestedAPI := ctx.GetDefinition(r)
if requestedAPI == nil {
logger.Error("Could not get API Definition")
rw.WriteHeader(http.StatusInternalServerError)
return
}
realIp := request.RealIP(r)
sessionObject := &user.SessionState{}
sessionObject = &user.SessionState{
OrgID: requestedAPI.OrgID,
Rate: 2,
Per: 5,
AccessRights: map[string]user.AccessDefinition{
requestedAPI.APIID: {
APIID: requestedAPI.APIID,
},
},
MetaData: map[string]interface{}{
"rate_limit_pattern": realIp,
},
}
logger.Info("Session Alias: ", sessionObject.Alias)
// Set session state using session object
ctx.SetSession(r, sessionObject, false)
logger.Info("Session created for request")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment