Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Add API Rate limiting to API documentation #2681

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

chronark
Copy link
Collaborator

@chronark chronark commented Nov 25, 2024

This PR adds the API Rate limiting.mdx file to the API documentation.

Summary by CodeRabbit

  • New Features
    • Introduced a comprehensive guide on API rate limiting, covering its importance, implementation strategies, and best practices.
    • Included practical examples and resources for developers to effectively manage API requests.

Copy link

vercel bot commented Nov 25, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 7:14pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 7:14pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 7:14pm
workflows ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 7:14pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 25, 2024 7:14pm

Copy link

changeset-bot bot commented Nov 25, 2024

⚠️ No Changeset found

Latest commit: 83c751f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Nov 25, 2024

📝 Walkthrough

Walkthrough

A new file, api-rate-limiting.mdx, has been added to the project, providing a comprehensive guide on API rate limiting. The document covers key concepts such as rate limits, throttling, quotas, and burst limits, along with best practices for implementation. It includes a practical example in Python using Flask and Redis, and references additional resources and strategies for effective rate limiting.

Changes

File Change Summary
apps/www/content/glossary/api-rate-limiting.mdx New file created, detailing API rate limiting concepts, best practices, and a practical implementation example.

Possibly related PRs

Suggested labels

Documentation, 🕹️ oss.gg

Suggested reviewers

  • mcstepp
  • perkinsjr

Warning

Rate limit exceeded

@chronark has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 28 minutes and 46 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 46b0691 and 83c751f.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (5)
apps/www/content/glossary/api-rate-limiting.mdx (5)

102-102: Improve key format to prevent conflicts

The current key format might lead to conflicts in a multi-tenant environment.

-            key = f"{request.remote_addr}:{request.endpoint}"
+            key = f"rate_limit:{request.remote_addr}:{request.endpoint}"

98-115: Add type hints and improve error handling

The code example would benefit from type hints and better error handling for production use.

Here's an improved version:

from typing import Callable, TypeVar, Any
from datetime import datetime

T = TypeVar('T')

def rate_limiter(max_requests: int, time_period: int) -> Callable[[Callable[..., T]], Callable[..., T]]:
    def decorator(f: Callable[..., T]) -> Callable[..., T]:
        @wraps(f)
        def decorated_function(*args: Any, **kwargs: Any) -> T:
            key = f"rate_limit:{request.remote_addr}:{request.endpoint}"
            
            try:
                pipe = redis_client.pipeline()
                pipe.get(key)
                pipe.incr(key, 1)
                pipe.expire(key, time_period)
                results = pipe.execute()
                requests = int(results[0] or 0)
                
                if requests >= max_requests:
                    retry_after = redis_client.ttl(key)
                    response = jsonify({
                        "error": "Rate limit exceeded",
                        "retry_after_seconds": max(0, retry_after)
                    })
                    response.headers['Retry-After'] = str(max(0, retry_after))
                    return response, 429
                
                return f(*args, **kwargs)
            except redis.RedisError as e:
                app.logger.error(f"Redis error: {str(e)}")
                return jsonify({"error": "Service temporarily unavailable"}), 503
            
        return decorated_function
    return decorator

66-66: Fix grammatical issues in the documentation

Several compound adjectives should be hyphenated when they modify a noun:

  • "API Rate Limiting Concepts" → "API-Rate-Limiting Concepts"
  • "rate limiting middleware" → "rate-limiting middleware"
  • "Rate Limiting Strategies" → "Rate-Limiting Strategies"
  • "Rate Limiting Techniques" → "Rate-Limiting Techniques"

Also, add an article before "retry":

  • "when to retry" → "when to make a retry"

Also applies to: 131-131, 134-134, 142-142, 147-147

🧰 Tools
🪛 LanguageTool

[uncategorized] ~66-~66: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...s for developers. ## Understanding API Rate Limiting Concepts API rate limiting involves re...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


146-148: Enhance the REST API headers section

The headers section should include a complete list of standard rate limit headers and their usage examples.

Consider adding these standard headers:

  • X-RateLimit-Reset: Timestamp when the rate limit will reset
  • X-RateLimit-Policy: Description of the rate limit policy
  • RateLimit-*: Standardized headers as per draft RFC

Example:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200
Retry-After: 60
🧰 Tools
🪛 LanguageTool

[grammar] ~147-~147: Before the countable noun ‘to’ an article or a possessive pronoun is necessary.
Context: ...e this header to inform clients when to retry after hitting a rate limit. - **Token B...

(IN_NN_CC_VBG)


150-150: Add a troubleshooting section

Consider adding a troubleshooting section that covers common rate limiting issues and their solutions:

  • Rate limit exceeded in microservices architecture
  • Handling rate limits in distributed systems
  • Debugging rate limit configuration issues
  • Common client-side handling patterns

Would you like me to help draft this section?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 46b0691 and 83c751f.

📒 Files selected for processing (1)
  • apps/www/content/glossary/api-rate-limiting.mdx (1 hunks)
🧰 Additional context used
🪛 LanguageTool
apps/www/content/glossary/api-rate-limiting.mdx

[uncategorized] ~66-~66: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...s for developers. ## Understanding API Rate Limiting Concepts API rate limiting involves re...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[uncategorized] ~131-~131: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...s. 2. express-rate-limit: A Node.js rate limiting middleware for Express applications. 3....

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[uncategorized] ~134-~134: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ... frequency to resources. ## Cloudflare Rate Limiting Strategies Cloudflare provides advance...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[uncategorized] ~142-~142: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ype of rate limit trigger. ## REST API Rate Limiting Techniques REST APIs can implement rat...

(EN_COMPOUND_ADJECTIVE_INTERNAL)


[grammar] ~147-~147: Before the countable noun ‘to’ an article or a possessive pronoun is necessary.
Context: ...e this header to inform clients when to retry after hitting a rate limit. - **Token B...

(IN_NN_CC_VBG)

Comment on lines +35 to +40
- url: https://www.example.com/api-rate-limiting
title: API Rate Limiting — Everything You Need to Know
- url: https://www.example.com/rate-limiting-best-practices
title: Best Practices and Configurations for Implementing Rate Limiting in APIs
- url: https://www.example.com/rate-limiting-guide
title: Everything You Need to Know About Rate Limiting for APIs
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 25, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace example.com URLs with actual resource links

The recommended reading section contains placeholder URLs using example.com. These should be replaced with actual, valid resource links to provide real value to readers.

Consider replacing these with links to reputable sources like:

  • AWS documentation on API rate limiting
  • Microsoft Azure API management documentation
  • Google Cloud API design guides

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Contributor

Choose a reason for hiding this comment

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

Noted

Copy link
Contributor

github-actions bot commented Nov 25, 2024

Thank you for following the naming conventions for pull request titles! 🙏

Comment on lines +35 to +40
- url: https://www.example.com/api-rate-limiting
title: API Rate Limiting — Everything You Need to Know
- url: https://www.example.com/rate-limiting-best-practices
title: Best Practices and Configurations for Implementing Rate Limiting in APIs
- url: https://www.example.com/rate-limiting-guide
title: Everything You Need to Know About Rate Limiting for APIs
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

app.run()
```

## GitHub Resources for API Rate Limiting
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Do we expect the user to search for these?
can we use links instead?
@p6l-richard

Copy link
Contributor

Choose a reason for hiding this comment

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

Noting:

  • exclude GitHub (or any particular) Resources from content generation
  • rename the "recommended reading" section from takeaways into "recommended resources" and have it include github link(s) if fitting

@chronark chronark self-assigned this Nov 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants