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

Increase orderbook mid price cache duration to 60 seconds #2633

Merged
merged 1 commit into from
Dec 10, 2024

Conversation

adamfraser
Copy link
Contributor

@adamfraser adamfraser commented Dec 9, 2024

Increases the amount of time we store orderbook mid price data from 30 to 60 seconds. This is to remedy spikes in candle data that we continue to see with 30 seconds of data.

Summary by CodeRabbit

  • Bug Fixes

    • Adjusted the timing in the getMedianPrice test case from 30 seconds to 60 seconds to ensure accurate median price verification.
  • Chores

    • Updated the time window for processing market prices from 30 seconds to 60 seconds in the relevant Lua script, including necessary comments.

Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

Walkthrough

The pull request modifies the orderbook-mid-prices-cache test suite and the Lua script for processing market prices. The key change involves updating the time window from 30 seconds to 60 seconds in both the test case for getMedianPrice and the Lua script add_orderbook_mid_prices.lua. This adjustment ensures consistency in timing across the test and the script, while the overall logic and structure of both remain unchanged.

Changes

File Change Summary
indexer/packages/redis/tests/caches/orderbook-mid-prices-cache.test.ts Adjusted the timing in the getMedianPrice test from 30 seconds to 60 seconds.
indexer/packages/redis/src/scripts/add_orderbook_mid_prices.lua Updated the time window from 30 seconds to 60 seconds, modifying variable names and comments accordingly.

Possibly related PRs

Suggested reviewers

  • dydxwill

Poem

🐇 In the land of prices, where time does play,
We’ve stretched it to sixty, for a clearer way.
The tests now align with the script's gentle flow,
Ensuring our data can accurately grow.
Hops of delight as we fine-tune the chase,
For every tick matters in this lively race! 🌟


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.

@adamfraser adamfraser marked this pull request as ready for review December 9, 2024 20:21
@adamfraser adamfraser requested a review from a team as a code owner December 9, 2024 20:21
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 and nitpick comments (2)
indexer/packages/redis/__tests__/caches/orderbook-mid-prices-cache.test.ts (2)

139-139: Verify test coverage for edge cases with new cache duration

The test has been updated to reflect the new 60s cache duration, but consider adding test cases for:

  1. Exactly 60s (boundary condition)
  2. 59s (just before expiry)
  3. Multiple cache cycles to ensure consistent behavior

Here's a suggested addition to improve test coverage:

 it('returns the correct median price after 60 seconds', async () => {
   // ... existing test code ...
 });
+
+it('handles boundary conditions for cache expiry', async () => {
+  jest.useFakeTimers();
+  const mockPrices = ['50000', '51000'];
+  
+  (OrderbookLevelsCache.getOrderBookMidPrice as jest.Mock)
+    .mockResolvedValueOnce(mockPrices[0])
+    .mockResolvedValueOnce(mockPrices[1]);
+
+  await fetchAndCacheOrderbookMidPrices(client, [defaultTicker]);
+  
+  // Test at exactly 60s
+  jest.advanceTimersByTime(60000);
+  let result = await getMedianPrices(client, [defaultTicker]);
+  expect(result[defaultTicker]).toBeDefined();
+  
+  // Test just before expiry
+  jest.advanceTimersByTime(59000);
+  result = await getMedianPrices(client, [defaultTicker]);
+  expect(result[defaultTicker]).toBeDefined();
+  
+  jest.useRealTimers();
+});

Also applies to: 157-157


157-157: Consider adjusting timer advancement for better clarity

The current test advances time by 61 seconds. While this works, using exactly 60 seconds would be more intuitive and align better with the actual cache duration. The extra second isn't necessary since Redis's ZREMRANGEBYSCORE is inclusive.

-jest.advanceTimersByTime(61000); // Advance time by 61 seconds
+jest.advanceTimersByTime(60000); // Advance time by exactly 60 seconds
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fc5ff36 and 64fa5e0.

📒 Files selected for processing (2)
  • indexer/packages/redis/__tests__/caches/orderbook-mid-prices-cache.test.ts (2 hunks)
  • indexer/packages/redis/src/scripts/add_orderbook_mid_prices.lua (2 hunks)
🔇 Additional comments (2)
indexer/packages/redis/src/scripts/add_orderbook_mid_prices.lua (2)

10-11: LGTM: Variable name change reflects new cache duration

The variable name change from thirtySeconds to sixtySeconds accurately reflects the new cache duration.


19-19: Consider memory usage impact with increased cache duration

Doubling the cache duration from 30s to 60s means Redis will store twice as much price data per market. While this helps smooth out price spikes, it's important to monitor Redis memory usage, especially for markets with high update frequencies.

Let's analyze the potential memory impact:

Also applies to: 34-34

✅ Verification successful

Based on the analysis of the code and configuration, I can now generate the final response:

Memory impact of increased cache duration is minimal and controlled

The Lua script implementation shows that Redis automatically removes old entries using ZREMRANGEBYSCORE, maintaining a fixed time window of data regardless of the duration. The change from 30s to 60s will have a linear and predictable impact:

  • Each market's price data is stored in a sorted set with timestamp-based cleanup
  • Old entries beyond the time window are automatically pruned
  • Memory usage scales linearly with update frequency × number of markets × time window
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check current memory usage pattern for price cache keys
redis-cli --eval "
local keys = redis.call('KEYS', 'orderbook-mid-prices:*')
local total = 0
local stats = {}
for _, key in ipairs(keys) do
    local size = redis.call('ZCARD', key)
    total = total + size
    stats[key] = size
end
return {total, stats}
"

Length of output: 376


Script:

#!/bin/bash
# Let's analyze the code to understand the memory impact
# First, let's find all references to this cache duration
rg "sixtySeconds" -A 3 -B 3

# Then check for any configuration or constants related to this duration
rg -i "cache.*duration|ttl" -A 2 -B 2

# Look for any Redis-related configuration files
fd -e yaml -e json -e toml -e conf . | xargs rg -i "redis"

# Check the Lua script usage pattern
rg "add_orderbook_mid_prices.lua" -A 3 -B 3

Length of output: 76502


Script:

#!/bin/bash
# Let's analyze the Redis usage pattern and memory implications
# First, check the Lua script implementation
cat indexer/packages/redis/src/scripts/add_orderbook_mid_prices.lua

# Look for any Redis configuration files or settings
fd -e ts -e js -e json . | xargs rg -i "redis.*config|redis.*option"

# Check for any memory-related configurations or settings
fd -e ts -e js -e json . | xargs rg -i "redis.*memory|cache.*size|cache.*limit"

# Look for any orderbook or price-related configurations
fd -e ts -e js -e json . | xargs rg -i "orderbook.*config|price.*config"

Length of output: 13163

@adamfraser adamfraser merged commit 7da33a6 into main Dec 10, 2024
16 checks passed
@adamfraser adamfraser deleted the adam/increase-candle-cache-time branch December 10, 2024 19:17
@adamfraser
Copy link
Contributor Author

@mergify backport release/indexer/v7x

Copy link
Contributor

mergify bot commented Dec 10, 2024

backport release/indexer/v7x

❌ No backport have been created

  • Backport to branch release/indexer/v7x failed

GitHub error: Branch not found

@adamfraser
Copy link
Contributor Author

@mergify backport release/indexer/v8.x

Copy link
Contributor

mergify bot commented Dec 10, 2024

backport release/indexer/v8.x

✅ Backports have been created

@adamfraser
Copy link
Contributor Author

@mergify backport release/indexer/v7.x

Copy link
Contributor

mergify bot commented Dec 10, 2024

backport release/indexer/v7.x

✅ Backports have been created

mergify bot pushed a commit that referenced this pull request Dec 10, 2024
mergify bot pushed a commit that referenced this pull request Dec 10, 2024
adamfraser added a commit that referenced this pull request Dec 11, 2024
…2633) (#2643)

Co-authored-by: Adam Fraser <adamfraser0@gmail.com>
adamfraser added a commit that referenced this pull request Dec 11, 2024
…2633) (#2642)

Co-authored-by: Adam Fraser <adamfraser0@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

2 participants