StreamingIntermediate

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.

Event LoopMarket EventStrategySignal EventRisk CheckOrder EventFill EventPortfolioevent-driven

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

AspectREST pollingWebSocket streaming
Who initiates each messageClient asks every timeServer pushes as events occur
LatencyPoll interval + round tripNear-instant on event
Overhead per updateFull request each timeMinimal after handshake
Rate-limit pressureHigh — many requestsLow — one connection
Best forActions & snapshotsLive 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?
A WebSocket is a persistent, bidirectional connection that starts as an HTTP request and is upgraded to a long-lived channel. After connecting, the broker pushes messages — ticks and order updates — to your program as events occur, without a new request per message.
How is a WebSocket different from REST?
REST is one-request-one-response and stateless per call, ideal for actions. A WebSocket stays open and streams data the moment it happens, ideal for live feeds. Trading systems use REST for orders and WebSockets for real-time ticks and fills.
What is a heartbeat in a WebSocket?
A heartbeat is a periodic ping/pong exchange that confirms the connection is alive. If expected pongs stop arriving, the client treats the connection as dead and reconnects, catching failures far faster than waiting for the OS to notice.
Why do I need to resubscribe after reconnecting?
Because the server does not remember your subscriptions across a new connection. A fresh WebSocket starts with no active subscriptions, so after reconnecting you must resend your subscription messages or the socket will be open but silent.
What happens to data I miss while disconnected?
It is lost from your stream — WebSockets do not replay missed messages. That is why, after any reconnection, you reconcile through REST by querying the order book and positions to recover the true state before resuming.
How should I handle reconnection?
Detect the drop via a missed heartbeat or close event, then reconnect using exponential backoff with jitter, re-authenticate if required, re-subscribe to all instruments, and reconcile state via REST. Never reconnect in a tight loop without backoff.
What is backpressure in streaming?
Backpressure is when messages arrive faster than your program can process them. If the consumer falls behind, buffers grow, latency rises and the broker may disconnect you. Keeping the read loop light and offloading work to another thread avoids it.
Can I stream every NSE instrument on one connection?
Usually not. Brokers cap the number of instruments per connection, so large universes are sharded across several connections. Each connection then needs its own heartbeat and reconnection handling, increasing the surface you must test.
Why is a half-open connection dangerous?
A half-open TCP connection looks open to the operating system but delivers no data, so your strategy can silently run on stale prices. An application-level heartbeat detects this in seconds, whereas the OS might take minutes.
Do WebSockets guarantee message order?
Over a single connection, TCP preserves order, but across a reconnect you can miss messages entirely, and multi-connection sharding can interleave streams. Your client must apply updates in order and reconcile after gaps to keep its book consistent.
Should order updates come over WebSocket or REST?
Both play a role. The WebSocket order-update stream tells you about fills and rejections in real time, but you should still confirm via REST — especially after a disconnect — because the stream can miss updates during a gap.
What format is tick data in?
Many Indian broker feeds send binary-packed ticks for efficiency, which your client decodes according to the documented byte layout, though some also offer JSON modes. Binary is faster and smaller but requires careful, version-aware parsing.
Is a WebSocket connection secure?
When it uses the secure wss:// scheme, the traffic is encrypted with TLS, like https. Authentication typically happens during the handshake using a token, so guard that token as carefully as any other secret.

Voice search & related questions

Natural-language questions people ask about WebSockets.

What is a WebSocket in simple terms?
It is an open phone line to your broker. Once connected, prices and order updates keep flowing to your code on their own, instead of you asking again for each one.
Why use a WebSocket instead of REST for prices?
Because streaming is near-instant and light, while polling REST is slow, wasteful and trips rate limits. For live ticks, the open connection wins easily.
What is a heartbeat and why does it matter?
It is a regular ping-pong that proves the line is still alive. If the pongs stop, you know the connection died and can reconnect quickly instead of trading on frozen prices.
What do I do after my connection drops?
Reconnect with a growing delay, re-subscribe to your instruments, and then check your orders and positions through REST, because the stream will not replay what you missed.
Can I miss my own order fills on a WebSocket?
Yes, if the connection drops during the fill. That is exactly why you reconcile with REST after reconnecting rather than trusting the stream alone.
Why not just reconnect instantly over and over?
Because during a broker outage that just hammers their servers. Use a growing, jittered delay so many clients do not all retry at the same instant.

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.

    Educational content only — not investment advice. Examples use illustrative numbers and simplified models. Algorithmic trading and derivatives involve substantial risk. See our Risk Disclosure and SEBI Disclaimer.