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

Add API Caching to API documentation #2738

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

Conversation

chronark
Copy link
Collaborator

@chronark chronark commented Dec 11, 2024

This PR adds the API Caching.mdx file to the API documentation.

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive guide on API caching, covering best practices and examples in multiple programming languages.
  • Documentation

    • Added a FAQ section addressing common questions about API caching and its strategies.

Copy link

vercel bot commented Dec 11, 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 Dec 11, 2024 7:33am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 11, 2024 7:33am
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 11, 2024 7:33am
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 11, 2024 7:33am

Copy link

changeset-bot bot commented Dec 11, 2024

⚠️ No Changeset found

Latest commit: dda1cef

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 Dec 11, 2024

📝 Walkthrough

Walkthrough

A new file named api-caching.mdx has been created, providing a detailed guide on API caching. It covers the definition, benefits, and drawbacks of caching, along with best practices and examples in various programming languages such as Java, C++, Python, and C#. The document includes sections on historical context, usage, and a FAQ to assist developers in implementing effective caching strategies.

Changes

File Path Change Summary
apps/www/content/glossary/api-caching.mdx New file created detailing API caching practices, benefits, drawbacks, and examples.

Possibly related PRs

Suggested labels

🕹️ oss.gg, :joystick: 50 points

Suggested reviewers

  • mcstepp
  • perkinsjr
  • MichaelUnkey

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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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

github-actions bot commented Dec 11, 2024

Hey there and thank you for opening this pull request! 👋🏼

We require pull request titles to follow the Conventional Commits specification and it looks like your proposed title needs to be adjusted.
Here is an example:

<type>[optional scope]: <description>
fix: I fixed something for Unkey

Details:

No release type found in pull request title "Add API Caching to API documentation". Add a prefix to indicate what kind of release this pull request corresponds to. For reference, see https://www.conventionalcommits.org/

Available types:
 - feat: A new feature
 - fix: A bug fix
 - docs: Documentation only changes
 - style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
 - refactor: A code change that neither fixes a bug nor adds a feature
 - perf: A code change that improves performance
 - test: Adding missing tests or correcting existing tests
 - build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
 - ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
 - chore: Other changes that don't modify src or test files
 - revert: Reverts a previous commit

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-caching.mdx (5)

6-6: Consider adding relevant categories

The categories array is currently empty. Consider adding relevant categories such as "Performance", "Optimization", or "Infrastructure" to improve content discoverability.


63-63: Consider rephrasing for clarity

The sentence could be more concise. Consider: "This decreases latency and alleviates server load, which is essential for improving user experience and efficiently handling high traffic."

🧰 Tools
🪛 LanguageTool

[style] ~63-~63: Opting for a less wordy alternative here can improve the clarity of your writing.
Context: ...lls made to the actual API server. This not only decreases latency but also alleviates server load, which is essential for imp...

(NOT_ONLY_ALSO)


75-82: Consider adding rate limiting best practices

The best practices section is comprehensive, but consider adding information about implementing rate limiting alongside caching to prevent cache stampedes and protect your API from abuse.


83-150: Add cache eviction policy documentation

The code examples would benefit from comments explaining cache eviction policies and memory management strategies. Consider adding documentation about:

  • Time-based eviction
  • Size-based eviction
  • LRU/LFU policies
  • Memory limits

152-152: Consider rephrasing for clarity

The sentence could be more concise. Consider: "Implementing these strategies enhances API performance and ensures a better user experience, especially during peak traffic periods."

🧰 Tools
🪛 LanguageTool

[style] ~152-~152: Opting for a less wordy alternative here can improve the clarity of your writing.
Context: ...mes. Implementing these strategies will not only enhance the performance of your APIs but also ensure a better experience for users, especial...

(NOT_ONLY_ALSO)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 18a9957 and dda1cef.

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

[style] ~63-~63: Opting for a less wordy alternative here can improve the clarity of your writing.
Context: ...lls made to the actual API server. This not only decreases latency but also alleviates server load, which is essential for imp...

(NOT_ONLY_ALSO)


[style] ~152-~152: Opting for a less wordy alternative here can improve the clarity of your writing.
Context: ...mes. Implementing these strategies will not only enhance the performance of your APIs but also ensure a better experience for users, especial...

(NOT_ONLY_ALSO)

Comment on lines +101 to +113
#include <unordered_map>
std::unordered_map<std::string, Product> productCache;

Product getProductById(const std::string& id) {
if (productCache.find(id) != productCache.end()) {
return productCache[id]; // Return cached data
} else {
Product product = fetchProductById(id); // Fetch from DB or API
productCache[id] = product; // Cache it
return product;
}
}
```
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add thread safety to C++ example

The current C++ implementation using std::unordered_map is not thread-safe. Consider using a mutex or a thread-safe cache implementation.

Here's a thread-safe version:

#include <unordered_map>
#include <mutex>

class ProductCache {
private:
    std::unordered_map<std::string, Product> cache;
    mutable std::mutex mutex;

public:
    Product getProductById(const std::string& id) {
        {
            std::lock_guard<std::mutex> lock(mutex);
            auto it = cache.find(id);
            if (it != cache.end()) {
                return it->second;
            }
        }
        
        Product product = fetchProductById(id);
        
        {
            std::lock_guard<std::mutex> lock(mutex);
            cache[id] = product;
        }
        
        return product;
    }
};

Comment on lines +123 to +128
@app.route('/product/<id>')
@cache.cached(timeout=50, key_prefix='product_')
def get_product(id):
# Code to fetch product
return product
```
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling to Python example

The Python example should include error handling and logging for cache misses or failures.

Here's an improved version:

from flask import Flask, jsonify
from flask_caching import Cache
import logging

app = Flask(__name__)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
logger = logging.getLogger(__name__)

@app.route('/product/<id>')
@cache.cached(timeout=50, key_prefix='product_')
def get_product(id):
    try:
        product = fetch_product(id)  # Your fetch logic here
        return jsonify(product)
    except Exception as e:
        logger.error(f"Error fetching product {id}: {str(e)}")
        return jsonify({"error": "Failed to fetch product"}), 500

Copy link
Contributor

@ogzhanolguncu ogzhanolguncu left a comment

Choose a reason for hiding this comment

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

I guess we'll extend this doc and cover things like caching in express.js, golang/fiber, hits/miss, consistency patterns etc... For now it looks good.

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