0/12
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:

  1. Add lastUpdate and THROTTLE_MS (use 300ms) variables
  2. At the top of updateStatus, check if enough time has passed since lastUpdate. If not, return { throttled: true, updates: updateCount } without publishing
  3. When the update goes through, set lastUpdate = now and return { throttled: false, updates: updateCount }
  4. In the component, show a "throttled" indicator when an update is skipped
  5. Add a trailing edge: when throttled, use setTimeout to 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
/