# Polling vs Webhooks vs WebSockets: Explained with a Karva Chauth Story

*By Devang Pandya · Cloud Tech by Devang · Cloud • DevOps • AI — Made Simple*

> This post is the full breakdown for the **Karva Chauth Reel**. If you came here after commenting **CHAAND**, welcome, and Happy Karva Chauth!

**The story in the Reel:** it is Karva Chauth night, and the whole house has one question: *"Chaand nikla kya?"* (Has the moon come out yet?)

- **Mummy** climbs to the roof every two minutes to check. Nothing has changed, but she keeps checking. That is **polling**.
- **Papa** says, *"I have told Sharma ji. When he sees the moon, he will call us."* Nobody checks. The news comes when the event happens. That is a **webhook**.
- **Didi** is on a video call from Australia, and the call stays connected all evening. Either side can talk at any moment. That is a **WebSocket**.

Below is the real tech behind each one, with examples, a comparison table and interview answers.

---

## 1. Polling: "Has anything changed?"

With polling, the **client asks the server on a timer**. Most of the time the answer is "no change".

```
Client (Mummy)                 Server (the sky)
   | -- GET /moon -------------->  |
   | <-- 200 {"visible": false} -- |
   |        ... 2 minutes ...      |
   | -- GET /moon -------------->  |
   | <-- 200 {"visible": false} -- |
   |        ... 2 minutes ...      |
   | -- GET /moon -------------->  |
   | <-- 200 {"visible": true} --- |   finally!
```

**Where you see it in real life:**

- **Job status checks.** You start a long video export or report. The API returns a `job_id` and the UI calls `GET /jobs/{id}` every few seconds until the status is `completed`.
- **CI/CD dashboards** and scripts that wait for a deployment to become healthy.
- **Fallback for missed events.** Razorpay's own docs suggest polling their payment API as a backup for business-critical flows, because webhooks are asynchronous.

**Long polling** is a smarter version. The client sends a request, and the server **holds it open** until there is news (or a timeout), then the client immediately asks again. Fewer empty answers, but each waiting client still holds a connection.

**The trade-off:** polling is the simplest thing that works, and it works through any firewall or proxy. But you pay for every empty request, and your data is only as fresh as your interval. Poll every 2 minutes and news can be up to 2 minutes late. Poll every second and you multiply the load on the server.

---

## 2. Webhooks: "Call me when it happens"

A webhook flips the direction. You give the provider a URL. When an **event** happens, the **provider sends an HTTP POST to your server**.

```
Your app (Papa)               Provider (Sharma ji)
   | -- register: POST /webhooks {url} --> |
   |                                       |  ... waiting, no traffic ...
   |                                       |  EVENT: moon visible!
   | <-- POST /hooks/moon {event} -------- |
   | -- 200 OK ------------------------->  |
```

**Real examples:**

- **Payments:** Stripe and Razorpay send events like "payment captured" or "refund processed", so you mark the order paid even if the customer closed the browser tab.
- **GitHub:** a `push` or `pull_request` event triggers your CI pipeline or a Slack bot.

Webhooks look simple, but production webhooks need four things:

**1. Verify the signature.** Your webhook URL is public, so anyone can POST to it. Providers sign each payload with a shared secret using HMAC-SHA256: Stripe in the `Stripe-Signature` header, GitHub in `X-Hub-Signature-256`, Razorpay in `X-Razorpay-Signature`. Compute the HMAC over the **raw request body** (do not parse and re-serialise the JSON first) and compare it in constant time.

**2. Respond fast, process later.** GitHub expects a 2xx within **10 seconds**, and Razorpay within **5 seconds**, or the delivery counts as failed. Validate, push the event onto a queue (SQS, RabbitMQ, Redis), return 200, and let a worker do the real work.

**3. Expect retries.** If you fail, providers retry. Stripe retries for up to **three days** with exponential backoff in live mode. Razorpay retries with exponential backoff for **24 hours**, then disables the webhook. GitHub does not retry automatically. You redeliver failed deliveries yourself from the UI or API.

**4. Be idempotent.** Retries mean **at-least-once delivery**: you will see the same event more than once. Store the event ID (`x-razorpay-event-id`, Stripe's `event.id`, GitHub's `X-GitHub-Delivery`) and skip events you have already processed. Otherwise you may ship the same order twice. Also do not assume order: an "updated" event can arrive before a "created" one, so fetch the current state when in doubt.

---

## 3. WebSockets: "Keep the line open"

A WebSocket is **one long-lived, two-way connection**. It starts as a normal HTTP request with an `Upgrade: websocket` header. The server replies `101 Switching Protocols`, and from then on both sides can send messages at any time over the same TCP connection (RFC 6455).

```mermaid
sequenceDiagram
    participant Ghar as Browser (Ghar, India)
    participant Didi as Server (Didi, Australia)
    Ghar->>Didi: GET /call  (Upgrade: websocket)
    Didi-->>Ghar: 101 Switching Protocols
    Note over Ghar,Didi: connection stays open
    Didi-->>Ghar: "Mummy, yahan chaand dikh gaya!"
    Ghar->>Didi: "Show us on camera!"
    Didi-->>Ghar: photo frame
```

**Real examples:** chat apps, live cricket scores, trading and crypto dashboards with ticking prices, multiplayer games, collaborative editors (two people typing in one doc), and live delivery tracking.

**The trade-off:** messages arrive in milliseconds with almost no per-message overhead. But each client holds an open connection, so the server is **stateful**. You need to think about connection limits, load balancers that support long-lived connections (sticky sessions or a pub/sub layer like Redis so any server can reach any user), heartbeats (ping/pong) to detect dead clients, and reconnect logic when mobile networks drop.

### The middle option: Server-Sent Events (SSE)

What if only the server needs to talk? Use **SSE**. The browser opens one HTTP connection with `EventSource`, and the server streams `text/event-stream` messages down it. It is one-way (server to client), runs over plain HTTP, and the browser **reconnects automatically**. It is great for notifications, live news feeds, build logs and streaming AI responses. If the client also needs to send a lot of data back in real time, move up to WebSockets.

---

## 4. Comparison table

| | Polling | Webhook | WebSocket |
|---|---|---|---|
| **Who starts** | Client asks on a timer | Provider calls you on an event | Either side, any time |
| **Direction** | Client → server (request/response) | Server → server (one-way push) | Two-way |
| **Latency** | Up to one poll interval | Near real-time (seconds) | Real-time (milliseconds) |
| **Server load** | High, many empty requests | Low, traffic only on events | Steady, open connection per client |
| **Complexity** | Lowest | Medium (public endpoint, signatures, retries, idempotency) | Highest (stateful connections, scaling, reconnects) |
| **Works for browsers?** | Yes | No, needs a public server | Yes |
| **Best for** | Job status, simple dashboards, fallback checks | Payments, Git events, server-to-server integrations | Chat, live scores, trading, games, collaboration |

A quick rule from the Reel: **checking again and again = polling. News when an event happens = webhook. Live, two-way, always open = WebSocket.**

---

## 5. Common mistakes

- **Polling too fast.** A 1-second interval across 100,000 clients is 100,000 requests per second, most of them returning nothing. Use backoff, or switch to webhooks or SSE.
- **Trusting webhook payloads without verifying signatures.** This is how fake "payment successful" events get your orders shipped for free.
- **Doing heavy work inside the webhook handler.** It times out, the provider retries, and now you have duplicates. Queue first, respond, then process.
- **No idempotency.** Duplicate events are normal behaviour, not a bug.
- **Using WebSockets for everything.** If data changes once an hour, an open connection per user is wasted cost. SSE or polling is enough.
- **No reconnect or heartbeat logic.** Mobile networks drop silently. Without ping/pong and retry with backoff, users stare at a "live" screen that stopped updating.
- **Webhooks with no fallback.** If your endpoint was down for a day, you need a reconciliation job that polls the provider's API to catch up.

---

## 6. Interview questions and crisp answers

**Q1. Polling vs webhooks: when would you pick each?**
Polling when I control only the client, updates are rare or I need a simple fallback. Webhooks when the provider supports them and I want near real-time events without wasting requests, for example payment confirmations.

**Q2. How do you secure a webhook endpoint?**
HTTPS only, verify the HMAC signature on the raw body with constant-time comparison, reject old timestamps to stop replays, optionally allowlist the provider's IPs, and keep the secret in a secrets manager.

**Q3. The same webhook event arrives twice. What do you do?**
Expect it, because delivery is at-least-once. I store each event ID with a unique constraint, process inside a transaction, and if the ID already exists I skip the work and still return 200 so the provider stops retrying.

**Q4. How would you build a live cricket score feed for millions of users?**
The score is mostly server to client, so SSE or WebSockets fan out from a pub/sub layer, with a CDN or edge layer if possible. I would use WebSockets if users also send things in real time, like chat or reactions. Clients reconnect with backoff and fetch the latest score on reconnect.

**Q5. How do you scale WebSockets horizontally?**
Load balancers that support long-lived connections, a shared pub/sub (Redis, Kafka or a managed service) so a message can reach a user on any server, heartbeats to clean dead connections, and connection limits per node with autoscaling on connection count.

**Q6. What is long polling and why is it not enough?**
The server holds the request until there is data, which cuts empty responses. But every waiting client still ties up a connection, and each message needs a new request, so for high-frequency two-way traffic WebSockets are more efficient.

---

### Sources
- Stripe Docs, "Receive Stripe events in your webhook endpoint" (Stripe-Signature, raw body, retries up to three days in live mode): https://docs.stripe.com/webhooks
- GitHub Docs, "Best practices for using webhooks" (respond within 10 seconds, X-GitHub-Delivery): https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks
- GitHub Docs, "Validating webhook deliveries" (X-Hub-Signature-256, constant-time compare): https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries
- Razorpay Docs, "Webhooks best practices" and "Validate and test webhooks" (24-hour retries, at-least-once, x-razorpay-event-id, X-Razorpay-Signature): https://razorpay.com/docs/webhooks/best-practices
- RFC 6455, "The WebSocket Protocol": https://www.rfc-editor.org/rfc/rfc6455
- MDN, "Using server-sent events": https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

---

> **Preparing for a Cloud, DevOps or SRE interview?** With 14+ years in Cloud & DevOps, I help engineers get interview-ready. Book a **Free 15-min Cloud & DevOps Interview Guidance Call** with me: what to study, how to answer system-design questions like this one, plus a CV and roadmap check 👉 [topmate.io/cloudtechbydevang](https://topmate.io/cloudtechbydevang/2358399)
>
> Follow **@cloudtechbydevang** on Instagram for more Cloud & DevOps interview prep, one story at a time. 🌕 Happy Karva Chauth!
