Skip to content

Add Proactive WatchDocument Connection Retry Mechanism with Exponential Backoff and Jitter#941

Closed
krapie wants to merge 5 commits intomainfrom
add-liveness-in-watchdocument
Closed

Add Proactive WatchDocument Connection Retry Mechanism with Exponential Backoff and Jitter#941
krapie wants to merge 5 commits intomainfrom
add-liveness-in-watchdocument

Conversation

@krapie
Copy link
Member

@krapie krapie commented Feb 2, 2025

What this PR does / why we need it?

This PR introduces a proactive retry mechanism for the WatchDocument connection, implementing exponential backoff and jitter). This optimization addresses several issues:

  1. It significantly reduces the frequency of connection retries when only one client is present at the document and the server's idle timeout causes disconnection due to lack of events. The previous approach resulted in 60 reconnections per hour, while the new mechanism will reduce this to approximately 7-8 reconnections, achieving an optimization of around 88%.
  2. It provides clients with greater flexibility in reconnecting. For instance, clients seeking a more sensitive collaborative editing experience can configure shorter backoff timeout values to reconnect more quickly in case of a split-brain scenario with the server.
  3. By adding jitter to the reconnection process, it prevents all clients from attempting to reconnect simultaneously when the server disconnects multiple connections. This reduces server overload by staggering reconnection attempts.

Additionally, the implementation respects server-side idle timeouts, ensuring that unused connections are cleaned up efficiently on both the server and client sides.

Any background context you want to provide?

This issue was originally derived from the Split-brain of Long-lived Connection (WatchDocument).

  1. The split-brain issue in WatchDocument occurred due to the Sharded Cluster Mode of the Yorkie Server.
  2. It was initially mitigated using an idle timeout (retry). This worked well in scenarios where clients were actively exchanging events, as the idle timeout would not trigger for active connections. However, a new problem arose—clients editing alone experienced frequent reconnections, with the system reconnecting every minute just to prevent the rare possibility of a split-brain issue.
  3. To address this, we are introducing proactive WatchDocument reconnection from the client, incorporating exponential backoff and jitter. This prevents excessive reconnections for clients editing alone, provides more configuration options for sensitive editing experiences, and helps prevent connection storms.

What are the relevant tickets?

Fixes #940

Checklist

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • New Features
    • Introduced configurable reconnection timeout settings that let users adjust the recovery behavior after periods of inactivity.
    • The client now automatically adapts and increases the delay between reconnection attempts—up to a maximum threshold—to improve error handling and connection stability.

@krapie krapie self-assigned this Feb 2, 2025
@coderabbitai
Copy link

coderabbitai bot commented Feb 2, 2025

Walkthrough

This PR introduces two new optional properties—idleStreamTimeout and maxIdleStreamTimeout—to the ClientOptions interface with default values of 60000 and Infinity, respectively. The DefaultClientOptions object is updated accordingly. The runWatchLoop method now accepts these additional parameters, integrating an idle timer mechanism and exponential backoff logic to monitor and abort stale connections. Methods like attach and changeSyncMode have been updated to pass the new timeout parameters, thereby refining the reconnection strategy and error handling.

Changes

File(s) Change Summary
packages/sdk/src/client/client.ts • Added optional properties idleStreamTimeout (default 60000) and maxIdleStreamTimeout (default Infinity) to ClientOptions
• Updated DefaultClientOptions
• Modified runWatchLoop signature to include idleStreamTimeout and maxIdleStreamTimeout
• Updated attach and changeSyncMode to pass new parameters

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant T as Timer
    participant S as Server/Event Stream
    participant R as Reconnector

    C->>T: Start idle timer (idleStreamTimeout)
    loop Watch Loop
        S-->>C: Emit event
        C->>T: Reset timer
    end
    alt Idle timeout exceeded
        T-->>C: Trigger timeout
        C->>R: Abort connection & schedule reconnect (exponential backoff up to maxIdleStreamTimeout)
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement connection liveness mechanism with automatic reconnection (#940)

Suggested reviewers

  • hackerwins

Poem

Hoppin' through the code, I twitch my little nose,
Idle timers set the pace where the quiet connection goes.
Exponential backoff on a moonlit byte,
Reconnecting gently in the digital night.
A bunny celebrates new tweaks with joyful hops and ASCII delights!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/sdk/src/client/client.ts

Oops! Something went wrong! :(

ESLint: 8.19.0

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/packages/sdk".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "packages/sdk/.eslintrc.js » ../../.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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. (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.

@krapie krapie added the enhancement 🌟 New feature or request label Feb 2, 2025
@krapie krapie force-pushed the add-liveness-in-watchdocument branch from 67aa970 to 8e0d499 Compare February 2, 2025 15:19
@codecov
Copy link

codecov bot commented Feb 5, 2025

Codecov Report

Attention: Patch coverage is 83.33333% with 6 lines in your changes missing coverage. Please review.

Project coverage is 78.52%. Comparing base (0754863) to head (34554e5).

Files with missing lines Patch % Lines
packages/sdk/src/client/client.ts 83.33% 4 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #941      +/-   ##
==========================================
+ Coverage   78.50%   78.52%   +0.02%     
==========================================
  Files          63       63              
  Lines        5419     5453      +34     
  Branches      997     1005       +8     
==========================================
+ Hits         4254     4282      +28     
- Misses        874      878       +4     
- Partials      291      293       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Member

@blurfx blurfx left a comment

Choose a reason for hiding this comment

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

Thank you for your contribution. I left a comment.

@hackerwins hackerwins marked this pull request as ready for review February 6, 2025 11:40
@hackerwins
Copy link
Member

I changed it to ready temporarily to activate CodeRabbit reviews.

Copy link

@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: 1

♻️ Duplicate comments (1)
packages/sdk/src/client/client.ts (1)

160-164: 🛠️ Refactor suggestion

Inconsistent default value in comment and code

The comment for reconnectionStreamTimeout states that the default value is 30000 ms, but in DefaultClientOptions, it is set to 60000 ms. Please update the comment or the default value to ensure consistency.

Apply this diff to correct the comment:

 /**
  * `reconnectionStreamTimeout` is the timeout of the reconnection stream. If
  * the stream is disconnected, the client waits for the timeout to reconnect
- * the stream. The default value is `30000`(ms).
+ * the stream. The default value is `60000`(ms).
  */
🧹 Nitpick comments (2)
packages/sdk/src/client/client.ts (2)

161-162: Improve wording in comment for clarity

The sentence "the client waits for the timeout to reconnect the stream" could be clearer. Consider rephrasing it to "the client waits for the timeout before attempting to reconnect the stream" for better clarity.

Apply this diff to rephrase the comment:

 * the stream is disconnected, the client waits for the timeout to reconnect
- * the stream.
+ * the stream before attempting to reconnect.

887-891: Extract magic number into a constant

The maximum timeout value 300000 ms (5 minutes) is hardcoded in the exponential backoff calculation. Consider extracting it into a named constant or making it configurable for better readability and flexibility.

Apply this diff to define a constant for the maximum timeout:

+        const MAX_RECONNECTION_TIMEOUT = 300000; // 5 minutes

And update the calculation:

          currentTimeout = Math.min(
            reconnectionStreamTimeout * Math.pow(2, consecutiveTimeouts - 1),
-           300000,
+           MAX_RECONNECTION_TIMEOUT,
          );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0754863 and 5786d04.

📒 Files selected for processing (2)
  • packages/sdk/public/index.html (1 hunks)
  • packages/sdk/src/client/client.ts (8 hunks)
🔇 Additional comments (1)
packages/sdk/public/index.html (1)

323-323: Verify the server port in client instantiation

The client is being instantiated with the URL 'http://localhost:80', changed from 'http://localhost:8080'. Ensure that the Yorkie server is correctly configured to listen on port 80. If the server is still running on port 8080, this change might cause connection issues.

@hackerwins hackerwins marked this pull request as draft February 6, 2025 11:46
@krapie krapie force-pushed the add-liveness-in-watchdocument branch from bddd46b to 3bd9eb4 Compare February 8, 2025 10:13
@krapie krapie force-pushed the add-liveness-in-watchdocument branch from 3bd9eb4 to ed17da5 Compare February 8, 2025 10:22
@krapie krapie marked this pull request as ready for review February 8, 2025 10:32
Copy link

@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

🧹 Nitpick comments (1)
packages/sdk/src/client/client.ts (1)

914-914: Consider using a more specific type for the timer.

Based on the past review comments, NodeJS.Timeout caused errors in other packages. Consider creating a custom type alias or using ReturnType<typeof setTimeout> instead of any.

-  let idleTimer: any;
+  let idleTimer: ReturnType<typeof setTimeout>;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5786d04 and ed17da5.

📒 Files selected for processing (1)
  • packages/sdk/src/client/client.ts (11 hunks)
🔇 Additional comments (4)
packages/sdk/src/client/client.ts (4)

158-171: Extract default timeout values as constants.

Consider extracting the default timeout values as named constants at the top of the file for better maintainability and reusability.

+const DEFAULT_IDLE_STREAM_TIMEOUT = 60000;
+const DEFAULT_MAX_IDLE_STREAM_TIMEOUT = Infinity;

const DefaultClientOptions = {
  syncLoopDuration: 50,
  retrySyncLoopDelay: 1000,
  reconnectStreamDelay: 1000,
-  idleStreamTimeout: 60000,
-  maxIdleStreamTimeout: Infinity,
+  idleStreamTimeout: DEFAULT_IDLE_STREAM_TIMEOUT,
+  maxIdleStreamTimeout: DEFAULT_MAX_IDLE_STREAM_TIMEOUT,
};

Also applies to: 181-182


246-249: LGTM!

The initialization of new timeout properties follows the existing pattern and correctly uses nullish coalescing for default values.


941-950: LGTM! Well-implemented exponential backoff with jitter.

The exponential backoff implementation with jitter is robust and follows best practices:

  • Base delay increases exponentially
  • Jitter adds randomization to prevent thundering herd
  • Maximum timeout is enforced

972-974: LGTM! Proper cleanup of timer resources.

The timer cleanup in the error handling path ensures no memory leaks.

Co-authored-by: changhui lee <iam@xo.dev>
@krapie krapie force-pushed the add-liveness-in-watchdocument branch from 527f085 to 34554e5 Compare February 8, 2025 17:04
Copy link

@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: 1

🧹 Nitpick comments (4)
packages/sdk/src/client/client.ts (4)

158-171: Add unit information to the documentation.

The documentation should specify that the timeout values are in milliseconds.

Apply this diff to improve the documentation:

   /**
-   * `idleStreamTimeout` is the timeout of the reconnection stream. If
-   * the stream is disconnected, the client waits for the timeout to reconnect
-   * the stream. The default value is `60000`(ms).
+   * `idleStreamTimeout` is the initial timeout in milliseconds for detecting idle
+   * connections. When no events are received within this duration, the client
+   * attempts to reconnect. The default value is `60000` milliseconds (1 minute).
    */
   idleStreamTimeout?: number;

   /**
-   * `maxIdleStreamTimeout` is the maximum timeout of the reconnection stream.
-   * If the stream is disconnected, the client waits for the timeout to reconnect
-   * the stream. The default value is `Infinity`(ms).
+   * `maxIdleStreamTimeout` is the maximum timeout in milliseconds that the
+   * exponential backoff can reach. This caps the delay between reconnection
+   * attempts. The default value is `Infinity` milliseconds.
    */
   maxIdleStreamTimeout?: number;

876-878: Reset backoff attempts on successful connection.

The backoffAttempts counter should be reset when the connection is successfully established, not just when events are received.

Add the reset in the initialization case:

   if (resp.body.case === 'initialization') {
+    backoffAttempts = 0;
+    currentTimeout = idleStreamTimeout;
     resolve([stream, ac]);
   }

941-951: Extract backoff calculation into a utility function.

The exponential backoff calculation could be extracted into a reusable utility function, making it easier to test and maintain.

Consider moving this logic to a separate utility function:

// In a separate utility file
export function calculateExponentialBackoff(
  baseTimeout: number,
  maxTimeout: number,
  attempts: number
): number {
  const exponentialDelay = baseTimeout * Math.pow(2, attempts - 1);
  const jitteredDelay =
    baseTimeout + Math.random() * (exponentialDelay - baseTimeout);
  return Math.min(jitteredDelay, maxTimeout);
}

// In the watch loop
const updateTimeoutWithBackoff = (): number => {
  backoffAttempts++;
  currentTimeout = calculateExponentialBackoff(
    idleStreamTimeout,
    maxIdleStreamTimeout,
    backoffAttempts
  );
  return currentTimeout;
};

914-928: Move timer management functions outside the promise callback.

The timer management functions could be moved outside the promise callback to improve code organization and reusability.

Consider refactoring the timer management into a class:

class IdleTimer {
  private timer?: ReturnType<typeof setTimeout>;
  private currentTimeout: number;
  private backoffAttempts: number = 0;

  constructor(
    private readonly baseTimeout: number,
    private readonly maxTimeout: number,
    private readonly onTimeout: () => void
  ) {
    this.currentTimeout = baseTimeout;
  }

  schedule(): void {
    this.clear();
    this.timer = setTimeout(() => {
      this.onTimeout();
      this.updateTimeoutWithBackoff();
      this.schedule();
    }, this.currentTimeout);
  }

  reset(): void {
    this.clear();
    if (this.backoffAttempts > 0) {
      this.backoffAttempts = 0;
      this.currentTimeout = this.baseTimeout;
    }
    this.schedule();
  }

  clear(): void {
    if (this.timer) {
      clearTimeout(this.timer);
    }
  }

  private updateTimeoutWithBackoff(): void {
    this.backoffAttempts++;
    this.currentTimeout = calculateExponentialBackoff(
      this.baseTimeout,
      this.maxTimeout,
      this.backoffAttempts
    );
  }
}

Also applies to: 929-940

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 527f085 and 34554e5.

📒 Files selected for processing (1)
  • packages/sdk/src/client/client.ts (11 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (18.x)
🔇 Additional comments (1)
packages/sdk/src/client/client.ts (1)

213-214: LGTM!

The client properties and constructor initialization are implemented correctly, with proper handling of default values.

Also applies to: 246-249

@krapie krapie requested a review from blurfx February 8, 2025 17:07
Copy link
Member

@hackerwins hackerwins left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution.

@krapie krapie changed the title Add Liveness Mechanism in WatchDocument Add Proactive WatchDocument Connection Retry Mechanism with Exponential Backoff and Jitter Feb 11, 2025
@krapie
Copy link
Member Author

krapie commented Feb 12, 2025

Closing this PR as the intention of this PR, which was to optimize WatchDocument reconnection for all clients, has changed. This is because the server's idle timeout is functioning as expected for most of the clients, and implementing this feature requires consideration of various client use cases.

@krapie krapie closed this Feb 12, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement 🌟 New feature or request

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Add Proactive WatchDocument Connection Retry Mechanism with Exponential Backoff and Jitter

3 participants