API Fundamentals Course
API Fundamentals
/
Beginner

Polling

Definition

A technique where a client repeatedly makes standard HTTP requests to a server at fixed intervals to check for new data.

Explain Like I'm New

A kid in the backseat on a road trip repeatedly asking 'Are we there yet? Are we there yet? Are we there yet?' every 5 seconds. The server answers 'No, No, No' until finally answering 'Yes'.

Real World Example

An order tracking page. The frontend runs a `setInterval` that does a `fetch('/api/order/status')` every 10 seconds to see if the pizza has been delivered yet.

Common Use Cases

  • •Simple status checks
  • •Legacy systems without WebSockets

Interactive Example

// Frontend React Example: Standard Short Polling

import { useEffect, useState } from 'react';

export default function OrderTracker() {
  const [status, setStatus] = useState('Cooking');

  useEffect(() => {
    // Ask the server every 5000 milliseconds (5 seconds)
    const intervalId = setInterval(async () => {
      const res = await fetch('/api/order/123');
      const data = await res.json();
      
      setStatus(data.status);
      
      // If delivered, stop asking!
      if (data.status === 'Delivered') {
        clearInterval(intervalId);
      }
    }, 5000);

    return () => clearInterval(intervalId);
  }, []);

  return <div>Status: {status}</div>;
}

Interview Questions

basic

  • Why is Short Polling considered highly inefficient?

intermediate

  • If you need real-time data but cannot use WebSockets, what is the best alternative to standard Polling?

Flash Cards

Question

Why inefficient?

Click to reveal answer
Answer

It wastes massive amounts of resources. If 1,000 users check their inbox every 5 seconds, that's 200 requests per second hitting the server, and 99% of those requests will return 'No new messages', wasting bandwidth and database CPU.

Question

Best alternative?

Click to reveal answer
Answer

Long Polling or Server-Sent Events (SSE).