10. Throttle
Lesson 10: Throttle
When an RPC is called on every keystroke or mouse move, the server can get flooded with updates. Throttling limits how often an action actually executes.
Timestamp-based throttle
The simplest server-side throttle uses Date.now() to track when the last update was accepted:
let lastUpdate = 0;
const THROTTLE_MS = 300;
export const update = live((ctx, value) => {
const now = Date.now();
if (now - lastUpdate < THROTTLE_MS) {
return { throttled: true };
}
lastUpdate = now;
// ... proceed
}); No timers needed - just compare timestamps. If the gap is too small, skip the update and tell the client it was throttled.
Try it
The starter code updates the status on every keystroke. Type quickly and watch the "Server updates" counter climb with each character. Your task:
- Add
lastUpdateandTHROTTLE_MS(use 300ms) variables - At the top of
updateStatus, check if enough time has passed sincelastUpdate. If not, return{ throttled: true, updates: updateCount }without publishing - When the update goes through, set
lastUpdate = nowand return{ throttled: false, updates: updateCount } - In the component, show a "throttled" indicator when an update is skipped
- Add a trailing edge: when throttled, use
setTimeoutto retry after 300ms so the final value always gets through
After adding the throttle, type quickly again - the counter should climb much more slowly. When you stop typing, the trailing edge ensures your last keystroke is delivered.
WebSocket
0
No messages yet