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

Optimised reading from cache #19627

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Optimised reading from cache #19627

wants to merge 5 commits into from

Conversation

allouis
Copy link
Contributor

@allouis allouis commented Jan 31, 2024

🍦

This ensures that concurrent reads from the cache do not make concurrent reads from the underlying data store.

cache: redisCacheInstanceStub
});

const fetchData = sinon.stub().resolves('Da Value');
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not sure how this test works reliably. Shouldn't we at least wait after both get calls before resoling the fetchData method?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We don't need to do that because we're not awaiting the calls to get - this test consistently fails without the changes and passes with them

Copy link
Contributor

@SimonBackx SimonBackx Feb 1, 2024

Choose a reason for hiding this comment

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

Okay, I'm still a bit skeptical because everything is still very synchronous and the executing already starts before awaiting the get calls, but we can just fix if it would ever start failing

@@ -98,6 +99,40 @@ describe('Adapter Cache Redis', function () {
}
});

it('can wait for execution in the case of duplicate reads', async function () {
Copy link
Contributor

@SimonBackx SimonBackx Jan 31, 2024

Choose a reason for hiding this comment

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

Preferably we should also add a test with a fetchData error

Copy link
Contributor

Our bot has automatically marked this PR as stale because there has not been any activity here in some time.

If we’ve missed reviewing your PR & you’re still interested in working on it, please let us know. Otherwise this PR will be closed shortly, but can always be reopened later. Thank you for understanding 🙂

@github-actions github-actions bot added the stale [triage] Issues that were closed to to lack of traction label Jan 24, 2025
Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

Walkthrough

The changes focus on improving the concurrency and efficiency of the Redis cache adapter in the Ghost project. A new currentlyExecutingReads Map is introduced to track ongoing read operations, preventing multiple simultaneous fetches for the same cache key. A private #get method is added to encapsulate cache retrieval logic, providing better separation of concerns. The modifications aim to optimize cache management by reducing redundant fetch operations and handling concurrent read scenarios more effectively.

Changes

File Change Summary
ghost/adapter-cache-redis/lib/AdapterCacheRedis.js - Added currentlyExecutingReads Map to track ongoing read operations
- Introduced private #get method to handle cache retrieval logic
- Modified get method to manage concurrent read operations
ghost/adapter-cache-redis/test/adapter-cache-redis.test.js - Added test case for cache miss and value retrieval
- Added test case for handling duplicate/concurrent reads

Sequence Diagram

sequenceDiagram
    participant Client
    participant CacheAdapter
    participant RedisCache
    participant FetchFunction

    Client->>CacheAdapter: get(key)
    alt Key not in currentlyExecutingReads
        CacheAdapter->>RedisCache: Check cache
        alt Cache miss
            CacheAdapter->>FetchFunction: Fetch data
            FetchFunction-->>CacheAdapter: Return value
            CacheAdapter->>RedisCache: Store value
        end
        CacheAdapter-->>Client: Return value
    else Key already in currentlyExecutingReads
        CacheAdapter-->>Client: Return existing promise
    end
Loading

The sequence diagram illustrates the enhanced caching mechanism, showing how concurrent reads for the same key are managed, and how the fetch operation is performed only once when needed.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @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: 0

🔭 Outside diff range comments (1)
ghost/adapter-cache-redis/lib/AdapterCacheRedis.js (1)

Line range hint 181-207: Re-throw or handle errors properly in #get.

When fetchData() or this.cache.get() fails, the error is logged but never exposed to the caller. This can mask problems in upstream code. Consider re-throwing the error or returning a fallback value to ensure failures aren't silently swallowed.

A possible fix:

 try {
     const result = await this.cache.get(internalKey);
     ...
 } catch (err) {
     logging.error(err);
+    throw err; // or return a fallback, depending on the desired behavior
 }
🧹 Nitpick comments (1)
ghost/adapter-cache-redis/test/adapter-cache-redis.test.js (1)

Line range hint 62-99: Great coverage for cache miss update scenario.

This test provides clear evidence that the cache is only updated once on a miss and subsequent reads reuse the cached data. This greatly improves efficiency. You might also consider adding a negative test (e.g., when fetchData throws an error) to ensure error conditions are handled gracefully.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3ed6fab and 80c4e91.

📒 Files selected for processing (2)
  • ghost/adapter-cache-redis/lib/AdapterCacheRedis.js (2 hunks)
  • ghost/adapter-cache-redis/test/adapter-cache-redis.test.js (2 hunks)
🔇 Additional comments (3)
ghost/adapter-cache-redis/test/adapter-cache-redis.test.js (1)

102-134: Consider adding a fetchData error scenario test.

As previously mentioned in older review feedback, testing how your code behaves when fetchData rejects ensures resilience under non-ideal conditions (e.g., network failures). Verifying that subsequent calls either retry or surface the error will improve reliability coverage.

ghost/adapter-cache-redis/lib/AdapterCacheRedis.js (2)

64-64: Good approach to handle concurrent reads.

Storing active read operations in a map prevents duplicate fetches, thereby reducing the load on the data store. This is aligned with your PR objective of optimizing concurrent cache reads.


170-179: Validate potential race conditions.

Although JavaScript is single-threaded, consider a quick defensive check in case a promise is removed from currentlyExecutingReads before it's retrieved (for instance, if code structure changes over time). A small verification can help you detect unusual concurrency issues in complex scenarios.

@github-actions github-actions bot removed the stale [triage] Issues that were closed to to lack of traction label Jan 24, 2025
@allouis allouis force-pushed the redis-cache-updates branch from 80c4e91 to d6d5838 Compare February 3, 2025 05:40
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.

5 participants