Skip to content

chore(clerk-js): Add random jitter for session cookie pooler interval #6066

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions packages/clerk-js/src/core/auth/SessionCookiePoller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@ import { createWorkerTimers } from '@clerk/shared/workerTimers';
import { SafeLock } from './safeLock';

const REFRESH_SESSION_TOKEN_LOCK_KEY = 'clerk.lock.refreshSessionToken';
const INTERVAL_IN_MS = 5 * 1_000;

/**
* Returns an interval in milliseconds with random jitter.
* Uses a base interval of 5 seconds and adds up to 1.5 seconds of random jitter.
* This randomization helps prevent synchronized polling requests across multiple clients.
*/
const getIntervalInMs = () => {
Copy link
Member Author

Choose a reason for hiding this comment

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

Just saw that we have to take SYNC_LEEWAY in consideration as well.

const jitter = Math.random() * 1500;
return 5 * 1_000 + jitter;
};

export class SessionCookiePoller {
private lock = SafeLock(REFRESH_SESSION_TOKEN_LOCK_KEY);
Expand All @@ -20,7 +29,7 @@ export class SessionCookiePoller {
const run = async () => {
this.initiated = true;
await this.lock.acquireLockAndRun(cb);
this.timerId = this.workerTimers.setTimeout(run, INTERVAL_IN_MS);
this.timerId = this.workerTimers.setTimeout(run, getIntervalInMs());
};

void run();
Expand Down