WebSockets
A WebSocket is a persistent, bidirectional connection over which a broker pushes real-time data — market ticks and order-status updates — to your program continuously, without a fresh request per message.
Quick answer: A WebSocket is a persistent, bidirectional connection over which a broker pushes real-time data — market ticks and order-status updates — to your program continuously, without a fresh request per message.
In simple words
A WebSocket is like leaving a phone line open instead of hanging up and redialling for every question. Once your code connects and subscribes to some instruments, the broker streams prices and order updates down the same line as they happen. You do not ask for each tick; they simply arrive, which is why it feels live rather than delayed.
Purpose
WebSockets exist because polling a REST endpoint repeatedly is too slow and too costly for real-time data; a persistent stream delivers ticks and fills the instant they occur, which live strategies and accurate order tracking require.
Visual explanation
WebSockets
Ticks and order updates flowing continuously over one persistent connection.
Professional explanation
Persistent, bidirectional, low-overhead
A WebSocket begins life as an ordinary HTTP request that is then upgraded to a long-lived TCP connection which both sides keep open. After the handshake, either side can send messages at any time with minimal per-message overhead — no new headers, no new connection, no fresh authentication per tick. This is the opposite of REST's one-request-one-response model. For a market feed the economics are decisive: a single subscribe message can trigger thousands of inbound ticks, each arriving as soon as the exchange publishes it, whereas achieving the same with REST would require thousands of polling requests and still lag reality.
Subscribe and message model
After connecting, your client sends a subscription message naming the instruments (and often the mode — full depth, quote, or just last-traded price) it wants. The broker then streams messages for those instruments until you unsubscribe or disconnect. Two logical channels usually coexist: the market-data stream (ticks, depth) and the order-update stream (your fills, rejections, modifications). Many brokers send binary-packed tick data for efficiency, which your client must decode according to the documented byte layout. Handling backpressure — the case where ticks arrive faster than you can process them — is your responsibility; a slow consumer can fall behind or be disconnected.
Heartbeats and detecting a dead connection
A silent TCP connection is ambiguous: no messages could mean a quiet market or a broken link. To disambiguate, WebSocket protocols use heartbeats — periodic ping/pong frames. The client (or server) sends a ping; the other side must answer with a pong within a timeout. If pongs stop arriving, the connection is presumed dead even though the socket may still look open at the OS level. Relying on the operating system alone to notice a dead connection is a classic mistake, because a half-open TCP connection can linger for minutes. An application-level heartbeat lets you detect the failure in seconds and trigger reconnection.
Reconnection and resubscription
Networks drop; the question is only how gracefully you recover. A robust WebSocket client treats disconnection as expected: on close or missed heartbeat it reconnects, re-authenticates if needed, and — critically — re-subscribes to all instruments, because the server does not remember your subscriptions across a new connection. Reconnection attempts should use exponential backoff with jitter so that a broker-side outage does not cause every client to hammer the server in a synchronised storm. The reconnect logic must be as carefully tested as the trading logic, since a feed that silently dies mid-session can freeze a strategy on stale prices.
The gap problem: what you miss while disconnected
The hardest part of streaming is not reconnecting but reasoning about the gap. While your socket was down, ticks were published and, worse, your own orders may have filled. The stream does not replay what you missed, so on reconnect you cannot assume your position book is current. The correct pattern is to reconcile via REST after every reconnection: query the order book and positions to learn the true state, then resume streaming. Treating the stream as the sole source of truth for orders — and skipping the REST reconciliation — is how automated systems act on a stale view after a blip.
Streaming feeds versus your local snapshot
A live tick stream gives you a continuously updating picture, but your strategy usually needs a consistent snapshot to compute on. The client therefore maintains an in-memory book — last price, best bid/ask, perhaps aggregated candles — updated on each tick, and the strategy reads that snapshot. Two engineering concerns follow: ensure updates are applied in order (out-of-order or dropped messages corrupt the book), and ensure the snapshot the strategy reads is internally consistent (not half-updated mid-tick). These are the same ordering and consistency concerns that formal event-streaming systems address, in miniature.
REST polling vs WebSocket streaming for live data
| Aspect | REST polling | WebSocket streaming |
|---|---|---|
| Who initiates each message | Client asks every time | Server pushes as events occur |
| Latency | Poll interval + round trip | Near-instant on event |
| Overhead per update | Full request each time | Minimal after handshake |
| Rate-limit pressure | High — many requests | Low — one connection |
| Best for | Actions & snapshots | Live ticks & order updates |
Practical example
Illustrative example (Indian market)
Suppose your intraday system trades Bank Nifty options. It opens one WebSocket, subscribes to the relevant strikes and to the order-update channel, and builds an in-memory book from the incoming ticks. Mid-session the connection drops for eight seconds. Your client detects it via a missed heartbeat within about two seconds, reconnects with backoff, re-subscribes to every strike, and then calls the REST order book and positions endpoints to confirm that no fill occurred during the gap. Only after reconciling does it resume trading. The specific instruments and timings are illustrative and not a recommendation.
Indian broker feeds such as Kite's ticker or SmartAPI's WebSocket stream commonly deliver binary-packed ticks and may cap the number of instruments per connection. If you need more symbols than one connection allows, you shard subscriptions across multiple connections — and each of those needs its own heartbeat and reconnection handling, multiplying the failure surface you must test.
Advantages
- Delivers ticks and order updates in near real time, the instant the exchange publishes them
- One persistent connection replaces thousands of polling requests, easing rate limits
- Low per-message overhead makes high-throughput market data feasible
- Bidirectional channel carries both market data and your own order-status updates
Limitations
- Connections drop; you must build heartbeat detection, reconnection and resubscription yourself
- The stream does not replay missed messages, so a gap requires REST reconciliation
- A slow consumer can fall behind under backpressure and be disconnected or read stale data
- Binary tick formats and per-connection instrument caps add parsing and sharding complexity
- OS-level socket state can show open while the connection is actually dead (half-open)
Common mistakes
- Relying on the OS to notice a dead connection instead of an application-level heartbeat
- Reconnecting but forgetting to re-subscribe, so the socket is open but silent
- Treating the stream as the sole source of truth for orders and skipping REST reconciliation after a gap
- Reconnecting in a tight loop without backoff, hammering the broker during an outage
- Ignoring message ordering, so an out-of-order or dropped tick corrupts the in-memory book
- Blocking the socket read loop with heavy computation, causing backpressure and disconnection
Professional usage
Professional feed handlers separate the network thread that reads the socket from the worker that processes ticks, so heavy computation never stalls the read loop and cause backpressure. They implement heartbeats, exponential-backoff reconnection with jitter, and automatic resubscription, and they always reconcile order and position state via REST after any reconnect. The feed's health — last-tick timestamp, reconnect count, gap duration — is monitored as a first-class signal, because a frozen feed is as dangerous as a wrong signal.
Key takeaways
- A WebSocket keeps one connection open so the broker can push live ticks and order updates continuously
- Use heartbeats to detect dead connections in seconds rather than trusting the OS socket state
- On reconnect you must re-subscribe and reconcile orders/positions via REST — the stream never replays gaps
- Reconnect with exponential backoff and jitter, and never let heavy processing block the read loop
Frequently asked questions
What is a WebSocket?
How is a WebSocket different from REST?
What is a heartbeat in a WebSocket?
Why do I need to resubscribe after reconnecting?
What happens to data I miss while disconnected?
How should I handle reconnection?
What is backpressure in streaming?
Can I stream every NSE instrument on one connection?
Why is a half-open connection dangerous?
Do WebSockets guarantee message order?
Should order updates come over WebSocket or REST?
What format is tick data in?
Is a WebSocket connection secure?
Voice search & related questions
Natural-language questions people ask about WebSockets.
What is a WebSocket in simple terms?
Why use a WebSocket instead of REST for prices?
What is a heartbeat and why does it matter?
What do I do after my connection drops?
Can I miss my own order fills on a WebSocket?
Why not just reconnect instantly over and over?
Sources & references
Last reviewed 11 July 2026. Educational content only — not investment advice. Markets and rules change; verify current conventions with SEBI, NSE/BSE and your broker.