Skip to content

Conversation

sedkis
Copy link
Contributor

@sedkis sedkis commented Sep 17, 2025

User description

Contributor checklist

  • Reviewed PR Code suggestions and updated accordingly
  • Tyklings: Labled the PR with the relevant releases
  • Tyklings: Added Jira DX PR ticket to the subject

New Contributors



PR Type

Documentation


Description

  • Add Go plugin rate limiter example

  • Demonstrate IP-based rate limit via metadata

  • Clarify usage with custom auth plugins

  • Reinforce session setup for rate limiting


Diagram Walkthrough

flowchart LR
  A["Custom Go plugin"] -- "extract RealIP" --> B["Build SessionState"]
  B -- "set rate/per + AccessRights" --> C["Set MetaData rate_limit_pattern"]
  C -- "ctx.SetSession(...)" --> D["Tyk Gateway rate limiter"]
  D -- "enforces per pattern/IP" --> E["Protected upstream"]
Loading

File Walkthrough

Relevant files
Documentation
rate-limit.md
Add Go example for IP-based rate limiting                               

tyk-docs/content/api-management/rate-limit.md

  • Add "Custom Plugin Rate Limiter Example" section.
  • Provide Go code for IP-based rate limiting.
  • Show session metadata usage (rate_limit_pattern).
  • Explain integration with custom authentication plugins.
+43/-0   

Copy link
Contributor

⚠️ Deploy preview for PR #6950 did not become live after 3 attempts.
Please check Netlify or try manually: Preview URL

Copy link
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Code Accuracy

The Go snippet references symbols like ctx.GetDefinition, request.RealIP, user.SessionState, and ctx.SetSession without imports or context; verify these match actual Tyk Go plugin SDK APIs and recommended method names (e.g., tykContext vs ctx, real IP extraction helper) to avoid misleading readers.

```go
// 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")
}

</details>

<details><summary><a href='https://github.com/TykTechnologies/tyk-docs/pull/6950/files#diff-f3fc2340f09caaef97b04c1e624a0ef0fca285bbf9ce7f7a5a74ee067422575dR353-R386'><strong>Example Completeness</strong></a>

The example sets Rate/Per and AccessRights but doesn’t show required imports, plugin hook signature, or how to attach the session to the request lifecycle; consider adding minimal imports and noting required plugin type and return behavior.
</summary>

```markdown
```go
// 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")
}

</details>

<details><summary><a href='https://github.com/TykTechnologies/tyk-docs/pull/6950/files#diff-f3fc2340f09caaef97b04c1e624a0ef0fca285bbf9ce7f7a5a74ee067422575dR363-R377'><strong>IP Extraction</strong></a>

Using request.RealIP may not account for proxies/X-Forwarded-For; clarify trusted proxy settings and which header/gateway config is used to derive the client IP to prevent incorrect rate limiting.
</summary>

```markdown
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,
	},

Copy link
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Security
Use a safe client IP source

Avoid using client-provided headers blindly for IP extraction, as RealIP may be
spoofable if proxy headers aren't trusted/sanitized. Use a trusted proxy chain or
gateway-provided remote address to derive the client IP safely.

tyk-docs/content/api-management/rate-limit.md [363]

-realIp := request.RealIP(r)
+// Derive client IP safely; avoid trusting unvalidated headers
+realIp := r.RemoteAddr
+if ip, _, err := net.SplitHostPort(realIp); err == nil {
+	realIp = ip
+}
Suggestion importance[1-10]: 6

__

Why: Highlights potential spoofing risk when using request.RealIP(r) and proposes a safer baseline using RemoteAddr; useful but context-dependent in docs and may vary with trusted proxy setup.

Low
General
Remove redundant initialization

Remove the redundant initialization of sessionObject to prevent confusion and ensure
the intended object is used. Initialize it once directly with the struct literal.

tyk-docs/content/api-management/rate-limit.md [365-378]

-sessionObject := &user.SessionState{}
-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,
 	},
 }
Suggestion importance[1-10]: 5

__

Why: Correctly identifies and removes an unnecessary pre-initialization of sessionObject, improving clarity without changing behavior.

Low

Copy link
Contributor

Code Review: PR #6950 - Update rate-limit.md

Overview

This PR adds a new "Custom Plugin Rate Limiter Example" section to the rate-limit.md documentation, demonstrating how to implement IP-based rate limiting using a custom Go plugin.

Technical Assessment

The code example provided is technically sound and follows Tyk's best practices:

  1. Proper IP extraction: Uses request.RealIP(r) which correctly handles proxies and X-Forwarded-For headers.

  2. Correct session configuration:

    • Sets appropriate rate limits (2 requests per 5 seconds)
    • Properly configures AccessRights for the API
    • Correctly uses the rate_limit_pattern metadata field
  3. Integration with Tyk's rate limiting system:

    • Properly calls ctx.SetSession(r, sessionObject, false) to associate the session with the request
    • Demonstrates how Tyk's rate limiting will be applied per IP rather than per token
  4. Documentation value:

    • Fills a gap in the existing documentation, which previously stated IP-based rate limiting was "not yet" possible (with only JavaScript middleware mentioned as a workaround)
    • Provides a clear, practical example that users can adapt for their own needs

Diagram Accuracy

The included mermaid diagram accurately represents the flow:

  1. Custom Go plugin extracts the real IP
  2. Builds a SessionState with rate/per and AccessRights
  3. Sets the MetaData rate_limit_pattern
  4. Uses ctx.SetSession to pass to Tyk Gateway rate limiter
  5. Gateway enforces rate limits per pattern/IP

Conclusion

This PR provides valuable documentation that clearly demonstrates how to implement IP-based rate limiting using custom Go plugins. The code is technically accurate and follows best practices. I recommend approving this PR.


Tip: Mention me again using /probe <request>.
Powered by Probe AI

Copy link

netlify bot commented Sep 17, 2025

PS. Add to the end of url /docs/nightly

Name Link
🔨 Latest commit 972225b
🔍 Latest deploy log https://app.netlify.com/projects/tyk-docs/deploys/68e51c4a42e2a6000809b4bc
😎 Deploy Preview https://deploy-preview-6950--tyk-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@sharadregoti sharadregoti changed the title Update rate-limit.md Configure Custom Rate Limiting using Custom Plugins Oct 3, 2025
@sharadregoti sharadregoti requested a review from andyo-tyk October 3, 2025 07:41
Copy link
Contributor

@andyo-tyk andyo-tyk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check the accuracy of some of my suggestions - in particular regarding multi-auth

@sharadregoti sharadregoti merged commit 40ec72e into master Oct 8, 2025
12 checks passed
@sharadregoti sharadregoti deleted the sedkis-patch-2 branch October 8, 2025 05:04
@sharadregoti
Copy link
Contributor

/release to release-5.8

@sharadregoti
Copy link
Contributor

/release to release-5.9

Copy link
Contributor

tykbot bot commented Oct 8, 2025

Working on it! Note that it can take a few minutes.

1 similar comment
Copy link
Contributor

tykbot bot commented Oct 8, 2025

Working on it! Note that it can take a few minutes.

Copy link
Contributor

tykbot bot commented Oct 8, 2025

@sharadregoti Created merge PRs

Copy link
Contributor

tykbot bot commented Oct 8, 2025

@sharadregoti Created merge PRs

buger added a commit that referenced this pull request Oct 8, 2025
…lugins (#6950)

Configure Custom Rate Limiting using Custom Plugins (#6950)
buger added a commit that referenced this pull request Oct 8, 2025
…lugins (#6950)

Configure Custom Rate Limiting using Custom Plugins (#6950)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants