Engineering

Bolt: Bi-directional Realtime Streaming Platform

Praveen Kumar25 November, 2026

URL copied to clipboard

When we started building PhonePe Invest, PhonePe’s stockbroking and mutual funds distribution platform, we needed a system that could power real-time features such as charts, prices, order updates, notifications, and so on.

Here are some of the key use cases we wanted the platform to solve:

  • Streaming of high frequency price feed to power charts, option chains and overall market view.
  • Delivery of events (order lifecycle events like confirmations, rejections and trades) and time-sensitive exchange or broker alerts (such as margin requirements for a trade or square off notifications)
  • Exchange feed distribution over external Developer APIs with the same reliability as our internal systems.
  • Change synchronization ensuring seamless state propagation and UX consistency across web and mobile applications.

Problem Characteristics & Challenges

Following are some of the important challenges that the system had to be resilient to.

  • Users flock to the app at the start of the market and towards closing of the market. This creates a thundering herd of incoming connections and disconnections which the system must be able to handle.
  • Market feed pushed by exchanges is often volatile and spikes at the start and end of the market. Any market events (earnings report, news) during the day may also cause spikes in order volume resulting in bursts of order lifecycle events and the tick rate. We should be able to handle these spikes while still maintaining the latency SLA.
  • Users could be on slow networks (2G/3G), may have jittery network performance, packet loss, connected through proxies, travelling, and so on. Problems such as half-open connections and backpressure arising out of these scenarios needed to be handled.
  • On low-end mobile devices, high rate, and volume of ticks needs to be handled efficiently, otherwise this leads to performance issues such as higher battery consumption, UI jank and overall slowness of the app. 
  • Using bloated protocols e.g. standard JSON for every price tick is inefficient in terms of memory and compute required to represent and encode/decode the messages. Pushing the word “price”: millions of times a second eats up massive bandwidth and increases costs. Binary formats (like Protocol Buffers) make the system faster but add a layer of complexity.
  • In a distributed feed distribution system, we must ensure that the latency is bounded and ensures fairness so that we offer a bounded SLA for every user.

Expected Scale

These are some of the numbers around which we started the design of the system. 

  • 1M concurrent persistent bi-directional connections
  • ~2L instruments (Equity, commodities, futures & options across exchanges such as NSE, BSE and MCX)
  • Assuming 5% of the instruments to be active, and each instrument publishing 3 price ticks per second on an average, expected incoming rate would be 0.05 * 2L * 3 ~ 30K messages/sec
  • For 1M connections, assuming avg of 30 msgs/sec publish rate across subscriptions and 50 bytes per message, bandwidth consumed would be 1M * 30 msgs/sec * 50 bytes = 1.5 GBps

Introducing Bolt

For users, a reliable and low latency market data stream is absolutely critical as all the investment and trading decisions depend on how the markets move. To be able to tackle all the problems we discussed earlier, we decided to build a system from ground up that allowed control over the various levers to extract performance, fits well into our current production architecture and has less overall operational maintenance.

Technical Decisions

Network Transport

We chose websockets as the primary transport to start with, due to its wide and native support in web browsers, extensive libraries, infrastructure compatibility and leveraging already existing web security standards like TLS (wss) as websockets start with standard HTTP/1.1 handshake. Other protocols such as Server Sent Events(SSE) are uni-directional and cannot support the dynamic nature of subscriptions/unsubscriptions. HTTP/2 is yet to be supported by the tail end of the browsers. Even for the browsers who do support HTTP/2, native bi-directional GRPC is not supported due to features such as HTTP2 trailers and binary framing control not being exposed to the javascript runtimes. 

Communication Protocol

Websockets handle the framing on top of the raw underlying TCP connection and allows exchange of both text and binary messages. We went ahead with a custom binary pub-sub protocol which allowed us to play with the raw binary messages and leverage various optimization techniques like zero copy for efficient distribution of messages across connections.

Programming Language & Frameworks

Java is the primary programming language used across PhonePe. For a realtime low-latency system, the preferred way usually is to use languages like C++, Rust etc. with manual memory management to avoid the pauses introduced by garbage collection as well as for overall faster computation.

We went ahead with Java in favour of overall tech stack standardization and easier developer operability, re-use of common platform libraries and infrastructure within PhonePe, and for simpler maintenance. With this, challenges such as native memory management, cache locality, boxing/unboxing, connection management at scale etc. needed to be solved. 

High Level Architecture

Core Components

There are essentially two main components in the bolt cluster:

  1. Bolt Broker : This is the end-user facing cluster of nodes on which the persistent connections land. Brokers essentially handle connections management, subscriptions management, efficient message processing, etc. Any updates originating from internal systems which could be user-aware(unicast/multicast) or topic-aware(broadcast), decisioning around user interests, and final dispatch is handled by the brokers. For instance, market feed which is volatile and user-agnostic is consumed directly by the brokers and dispatched to the user as per their subscriptions. Bolt Broker also runs market feed listeners and takes care of fan-out of market feed to the users. 
  1. Bolt Dispatcher: This is the internal-facing service through which all user-aware requests-to-push are routed through. Dispatcher maintains the state of the cluster and knows which users are on which nodes of the broker. Given a message that needs to be pushed to a user, the dispatcher looks up the list of broker nodes where the user is currently connected to and then calls those broker nodes to push the message to the user.

Dispatcher <-> Broker Interaction (Unicast/Multicast Flows)

This flow is used for all unicast/multicast use cases where a message is pushed to a set of users. 

Broker emits lifecycle events(connections, disconnections, subscriptions etc.) which are used by Dispatcher to maintain a mapping of user-> broker nodes. Whenever a request arrives at Dispatcher to push a message to a user, Dispatcher looks up all the nodes a user may be connected to, and calls each of those nodes in parallel to push the message. This mapping is maintained in an in-mem grid at Dispatcher for fast membership lookups. 

Dispatcher also maintains all the persistent topics and the associated metadata such as QOS, delivery constraints etc. which are change propagated to Broker nodes for topic validations during subscriptions.

Feed Distribution Flow

At any point of time, there could be thousands of users connected to a single broker node. Each of these users may be interested in 100s of topics across the complete topic space as per the state of the listeners (app). For example, if a user is viewing the option chain of a stock, the user will need to subscribe to all the options for real-time pricing information which are visible in the viewport. If there are 10000 connections on a broker node, 100s of topics per connection on an average would result in ~1M message fanouts that the broker needs to handle.

Optimization Strategies

Connection Sharding

To handle this fanout efficiently in the broker, instead of maintaining a single, massive global routing table that maps a topic directly to every connected user, we split the routing into two tiers: the Distribution Groups Manager (DGM) and the local shards (Distribution Group) arranged hierarchically. A DG is essentially a logical sub-group of connections currently on that node and maintains a mapping of topic -> connections. DGM maintains a mapping of topic -> DGs.

Whenever a connection arrives, the connection is assigned to one of the Distribution groups as per the load distribution. A Distribution Group has its own ring-buffer, a topic-> connection mapping and a processor thread that handles fan-out to the connections.

When a user subscribes to a topic on this connection, the DG adds a mapping of topic -> connection to its table and then informs DGM that it is interested in this topic. DGM in-turn updates its internal mapping of topic -> DG. 

For distribution of a message M{id=1, topic=T}, DGM first looks up in its table for all DGs interested in topic T and then calls each of these DGs to push the messages. These DGs enqueue the message identifier in their local ring-buffer. The processor thread then picks up the message, looks up all connections interested in the topic, and then notifies each of these connections to push the message M which essentially enqueues this message in the local app-level queue. 

In the fanout path, the system essentially enqueues the market feed packets in the connection level queues of all the connections interested in that topic. 

To push these messages on the connections, a DG also has a pusher thread, which periodically runs a push loop and initiates message push on the connections. All pending messages on a specific connection are batched and pushed as a single message. If the connection is not writable which could be due to rate limiting, the user being on a slow network, drop in packets, etc., bolt drops the message in favour of pushing more recent messages. 

Zero Allocation

In the hot path of market feed consumption and fanout, frequent short-lived object creation and allocation increase Garbage Collection (GC) pressure and high resource consumption, leading to pauses and ultimately “Stop-The-World” (STW) pauses that impact the whole system and negatively impact latency.

We employed various techniques like pooling & recycling of objects and ByteBuf wrappers on heap, and used pooled memory allocators for off-heap buffers to reduce overall object allocations in the hot path to reduce GC pressure and minimize the chances of STW pauses.

Since the native/direct memory is outside the control of the JVM, Netty employs reference counting to manage the lifecycle of the references to direct memory, reclaiming or adding the allocated memory back to the pool when the reference count becomes zero.

Direct I/O (Zero copy & Direct buffers)

Normally, consuming byte arrays of market packet would require copying bytes from kernel to the user space and then again copying of assembled bytes from user space to kernel space as per the user’s subscribed topics. This wastes CPU cycles and increases memory pressure if not managed well.

We leveraged Netty’s CompositeByteBuf, which creates a single logical view of multiple buffers (on/off heap). This allowed the system to add metadata and combine packets without ever physically duplicating the data in memory. For example, memory for a feed packet of ABC stock, would be allocated only once off heap globally, and then would be referenced and composed in a CompositeByteBuf as per the connection’s subscription state. This allows us to allocate memory in the order of market feed rate and not in the order of connections or subscriptions.

Data Structures

As per our load tests, we found that in the hot path, standard Java collections we used cause significant overhead and GC pressure due to the autoboxing and unboxing of primitive types (like long and int).

To solve this, we leveraged high-performance data structures from libraries like jctools and Eclipse Collections, such as NonBlockingHashMapLong, to avoid boxing. We also built a custom IndexableIntHashSet for the fan-out path to provide fast membership checks and dense iteration without allocations.

Pre-computed Feed Views

Bolt has the concept of event types in a topic where a user can subscribe to one or more event types for a given topic. The event types are essentially views of the data that flows in the topic. For market feed, topic maps to a given stock while event types correspond to one of LTP, Quote, Market Depth or Greeks. This allows the app to subscribe/unsubscribe data as per the section the user navigates to and allows the server to send data that is absolutely needed. 

Over the complete app lifecycle, a user may subscribe & unsubscribe to hundreds of topics and event types. At the level of a broker node, there may be tens of thousands of connections each with its own subscription state. On an average if a connection subscribes to 50 topics and 2 event types per topic, with 10000 connections per node, naively we would have to build and push ~1M new messages/sec which will definitely not scale in terms of the resources required to fan out these messages. 

Within a single topic, the LTP, Quote, Market Depth and Greeks payloads are identical across all subscribers; the only variable is which subset of event types a given connection has subscribed to. So, rather than constructing a bespoke message for each connection at delivery time, we construct each message once at publish time and allow every connection to reference the variant it requires. When a message to be published arrives on a topic, we decompose it into its constituent event types and pre-generate the payloads for the relevant combinations. All these combinations can be looked up by message IDs derived by bit masking techniques on the original message ID and the event types.  Due to this, the delivery of messages is just assembling references from this shared pool of messages(all allocated off-heap) and makes the overall fanout path super efficient.

Operational Stability & Safeguards

Rate Limiting & Moderation

Connection creation, subscribe rate, the number of topics that can be subscribed were added to ensure fair resource usage. 

Connection Lifecycle Management

The users could be on networks with varying quality of service(2G, 3G, Wifi), device capabilities, proxies etc which usually make the connections flaky and the data transfer jittery. To ensure liveness of the connections, we maintain a ping-pong cycle between the client & server to clean up idle connections.

The system also tracks and enforces bandwidth consumed at each connection level for limiting overall b/w usage and starts dropping older messages if the connection becomes non-writable due to higher b/w usage.

Security

For connections from the web apps, since the Auth token needs to be sent as query params and can get logged in intermediate paths, Bolt enforces a single token use policy. If the token is used to re-initiate a connection, bolt forcefully disconnects in the websocket upgrade path itself.

As these web socket connections are long running, to ensure that the user remains authenticated over the connection lifecycle, we have a lease based auth renewal flow performed on the same connection. Bolt notifies the app to re-generate the auth token at regular intervals before the expiry. If the app fails to regenerate and pass the new lease token, Bolt forcefully disconnects.

Load Testing

To ensure our system stays stable when a million users connect at once, we need to test it using real-world scenarios to find any weak spots. We can do this by simulating how people actually use the app, such as connecting and disconnecting at different speeds or changing their topic subscriptions, which alters how much data the servers need to handle. We also need to include basic background system checks and sudden spikes in high traffic to ensure the system can handle the stress. 

We built a distributed load testing system with a single control plane that could distribute the load test plans over a cluster of machines used to create these connections. The test plan consisted of specs such as connection ramp up, user traffic generation, and then disconnections and allowed us to test the system under various loads. The system also aggregates system and app performance metrics across the nodes such as the receive rate, message latencies, connection creation rates and failures, file descriptor creations, send and receive buffers behaviors and so on. 

Current Scale

Concurrent connections

This essentially represents the number of users interacting concurrently with the app and we usually peak around 1.6 to 2M concurrent connections during high traffic periods. 

Incoming connection rate

This is the rate at which devices create concurrent connections to Bolt. We hit a peak of ~ 35k connections/second and this  is usually between 6-8PM when there is a surge in concurrent transactions. 

Egress Rate

This is the rate at which the system pushes messages on the connections. This peaks to ~75K messages per second.

Impact

Bolt was built as a platform and is being leveraged in PhonePe for optimizing some of the following problems:

Faster overall Transactions

During a payment transaction on the PhonePe app, the app polls for the transaction state from a central transaction store. A transaction may involve multiple internal and external parties having different levels of responsiveness during the day which directly impacts the e2e transaction time. At scale, this results in waste of resources during the polls both in the app and at the backend.

We leveraged bolt push to notify the app to pull the transaction state whenever there was a state change in the transaction store combined with delaying polls at the app-level if the app was connected to Bolt. This led to a decrease in end-end transaction completion time by around 40% at p90. 

Mailbox

PhonePe’s API gateway has the capability to decompose certain backend API interactions that are inherently latent into a forward API call + a series of status calls instead of a single API call that spans tens of seconds. Once the backend service has generated the response, it notifies the gateway. The gateway acts as a mediator for handling the intermediate status calls and returns the final response to the app once available.

To optimize the latency of e2e mailbox calls, once the API gateway receives the response from upstream services, it initiates a bolt push of the final response as well resulting in a faster response resolution and reduced latencies.

As a result of a poll to push based optimization, the latency of mailbox resolution calls dropped by 75% at p90.