Skip to content

Instantly share code, notes, and snippets.

@nicolasmelo1
Last active September 18, 2025 18:45
Show Gist options
  • Select an option

  • Save nicolasmelo1/61e0b26996d9547d74980433d7b955a2 to your computer and use it in GitHub Desktop.

Select an option

Save nicolasmelo1/61e0b26996d9547d74980433d7b955a2 to your computer and use it in GitHub Desktop.
import { metaRateLimitEventEmitter } from './MetaRateLimiterProvider.tsx'
// Do what you gotta do then
metaRateLimitEventEmitter.publish('rateLimitExceeded')
else {
metaRateLimitEventEmitter.publish('rateLimitDismissed')
}
type EventTypes = 'rateLimitExceeded' | 'rateLimitDismissed'
function simplePubSub() {
const callbacks = new Map<symbol, (event: EventTypes) => void>
return {
subscribe: (callback: (event: EventTypes) => void) => {
const key = Symbol()
callbacks.set(key, callback);
return () => callbacks.delete(key)
},
publish(event: EventTypes) => {
for (const callback of callbacks.value()) {
callback(event)
}
}
}
}
export const metaRateLimitEventEmitter = simplePubSub();
export const MetaRateLimitProvider = ({ children }: React.PropsWithChildren) => {
const isRateLimited = Boolean(window.localStorage.get('isRateLimited') || false);
const backoffTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
function backoffStrategy(backoffCount: number = 0) {
if (backoffTimeoutRef.current) clearTimeout(backoffTimeoutRef.current);
const baseDelayMs = 60 * 1000;
const maxBackoffCount = 5;
const currentBackoffCount = Math.min(backoffCount, maxBackoffCount);
const delayMs = baseDelayMs * Math.pow(2, currentBackoffCount);
backoffTimeoutRef.current = setTimeout(() => {
// Make lightweight api call.
backoffStrategy(currentBackoffCount + 1);
}, delayMs);
}
React.useEffect(() => {
if (isRateLimited) backoffStategy();
return metaRateLimitEventEmitter.subscribe((event) => {
if (event === 'rateLimitExceeded') {
window.localStorage.set('true')
backoffStrategy()
} else if (event === 'rateLimitDismissed' && backoffTimeoutRef.current) clearTimeout(backoffTimeoutRef.current)
})
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment