Real-Time Market Data: Collection, Validation, and Low-Latency Push Design

    Real-time market data is the shared foundation for quote display, quantitative analysis, and risk control systems. Starting from a single quote snapshot, this article rebuilds a production-grade real-time market data pipeline: how to decouple static metadata from dynamic quote fields, which numeric and range constraints can be validated automatically, how to handle out-of-order data with event time and watermarks, how to batch and apply back-pressure on long-lived push connections, and which metrics, alerts, and failure drills belong in operations. It includes Java examples, validation rule tables, storage and protocol comparisons, a troubleshooting quick reference, and a launch checklist.

    Real-time market data is the shared foundation for quote display, quantitative analysis, and risk control systems. A single record looks simple: name, symbol, market, currency, price, open, previous close, high, low, update time. Behind it sits a chain of multi-source ingestion, cleaning and validation, stream computation, long-lived connection push, and monitoring and alerting. Any weak link can produce price jumps, wrong change percentages, delayed quotes, or even mislead trading decisions.

    This article starts from one quote snapshot and rebuilds an implementable real-time market data engineering design.

    1. From a Single Snapshot to the Full Pipeline

    Take a typical quote snapshot:

    1. Name: Example Symbol A Symbol: SYMBOLA Market: US Currency: USD
    2. Last: 282.1 Open: 284.275 Prev Close: 265.29
    3. High: 285.1354 Low: 275.36 Quote Time: 2026-11-24 11:30:30

    The record splits into three field groups:

    • Static metadata: name, symbol, market, currency. These change rarely and are good cache candidates.
    • Dynamic quote fields: last price, open, previous close, high, low. These change continuously during trading and require high-frequency writes and real-time push.
    • Time information: the quote timestamp. It determines whether the data is fresh, and whether consumers can handle out-of-order and delayed messages correctly.

    Run a full numeric consistency check:

    • Daily range: (285.1354 - 275.36) / 265.29 = 9.7754 / 265.29 ≈ 3.68%.
    • Change versus previous close: (282.1 - 265.29) / 265.29 = 16.81 / 265.29 ≈ 6.34%.
    • The open of 284.275 is above the previous close of 265.29, so this is a gap up.
    • The last price of 282.1 is close to the day’s high of 285.1354, placing it in the upper part of the day’s range.

    Two engineering conclusions follow:

    1. Quote fields have strong constraints between them. For example, the high must never be below the low, the open should fall inside the day’s range, and the last price should also fall between the day’s high and low. These constraints are a natural hook for data quality validation.
    2. Derived metrics such as change percentage and range are fully computable from raw fields. Their accuracy depends on raw data quality, the time basis, and precision control.

    A real-time market data service typically breaks into seven layers:

    1. Sources: exchange feeds / data vendors / internal market data systems
    2. Ingestion: multi-source access / shard scheduling / retry / circuit breaking
    3. Validation: format / range / baseline / time series
    4. Storage: latest snapshot / time-series detail / object storage archive
    5. Compute: stream processing / derived metrics / late data and watermarks
    6. Push: long-lived connection gateway / batch aggregation / back-pressure and rate limiting
    7. Display: web / mobile / large screen / open API

    Before implementation details, capacity and latency budgets are needed. For ten-thousand-scale symbols at the market open peak, the estimate might look like this: if 100,000 quote updates arrive per second and 10,000 connections each subscribe to all symbols, then compute throughput, message queue backlog, gateway connection count, memory usage, and bandwidth all have to be evaluated together. Latency targets can be decomposed as well: ingestion receive P95 under 100 ms, validation and compute P95 under 50 ms, gateway-to-client push P95 under 100 ms, and end-to-end P95 around 250 ms. Actual targets should be adjusted to the market, the network, and the client form factor.

    2. Data Modeling: How Do You Decouple Static Metadata from Dynamic Quotes?

    The most common modeling mistake is retransmitting and rewriting the name and symbol with every quote update. In practice, name, market, and currency are relatively stable, so they can be delivered once at first client load and then cached. The push channel only needs to carry dynamic fields such as symbol, price, and time.

    At minimum, split the model into two types:

    1. import java.math.BigDecimal;
    2. public record QuoteMeta(
    3. String symbol, // Symbol, e.g. SYMBOLA
    4. String name, // Display name
    5. String market, // Market, e.g. US
    6. String currency // Currency, e.g. USD
    7. ) {}
    8. public record QuoteUpdate(
    9. String symbol, // Symbol
    10. BigDecimal price, // Last price
    11. BigDecimal open, // Open price
    12. BigDecimal prevClose,// Previous close
    13. BigDecimal high, // Day high
    14. BigDecimal low, // Day low
    15. long volume, // Incremental volume
    16. long eventTimeMs, // Quote time, i.e. event time
    17. long receiveTimeMs, // Time the system received this record
    18. String source, // Data source
    19. long sourceSeq // Monotonically increasing sequence within one source
    20. ) {}

    The benefits: lower bandwidth consumption, smaller push messages, and independent sharding and scaling of the quote data path.

    Time semantics must be explicit. At least four kinds of time should be distinguished:

    • Quote time: when the price change actually happened. Used for computation, out-of-order detection, and window assignment.
    • Receive time: when the market data system received the record. Used to measure end-to-end latency.
    • Processing time: when the stream computation task handled the record. Used to monitor backlog.
    • Push time: when the record was sent down a long-lived connection to the client. Used to evaluate the end-user experience.

    Keeping only one “update time” invites misunderstanding. In production, store at least quote time and receive time; their difference reflects the latency of the data path.

    Price precision should not be handed to binary floating point. Two approaches are recommended:

    • Use a high-precision decimal type, such as Java’s BigDecimal.
    • Use integers scaled to the minimum price increment.

    If you go the integer route, you need an executable rule. For example, scale uniformly by 10000:

    1. int scale = 10000; // Configurable per market, e.g. 100 or 10000
    2. long units = price.multiply(BigDecimal.valueOf(scale)).longValueExact();

    If the number of decimals exceeds what scale can express, longValueExact() throws an exception instead of silently truncating. One caveat: the 282.1, 284.275, and 285.1354 in the example are there to demonstrate precision issues, and do not mean every market allows three or four decimals. US single-stock quotes, for instance, typically have a minimum increment of 0.01 USD, while other markets and instruments must configure precision according to their own rules.

    3. Ingestion Layer: How Do You Guarantee Stable Access Across Multiple Sources?

    Market data sources fall into two broad categories:

    • Push-based: the server actively pushes incremental updates. Good timeliness, but sessions and connections must be maintained.
    • Pull-based: the client requests snapshots at fixed intervals. Simple to implement, but timeliness is bounded by the polling period.

    In production, connect at least two independent sources and define a primary/backup relationship:

    1. Use the primary source directly while it is healthy.
    2. Switch to the backup automatically when the primary misses a heartbeat or produces no changes for a long period.
    3. After the primary recovers, switch back only after an observation period, to avoid flapping.
    4. Keep a source tag on both, for cross-validation and incident forensics.

    Symbol counts are often in the tens of thousands. Single-threaded serial ingestion can neither guarantee timeliness nor avoid triggering source-side rate limits. A sound approach:

    • Shard by symbol hash and distribute tasks evenly across multiple ingestion workers.
    • Apply per-source rate limiting with a token bucket or similar mechanism.
    • Retry with exponential backoff plus random jitter, to avoid retry storms.
    • Trip a circuit breaker when consecutive failures reach a threshold, pause requests briefly, and alert.

    After a circuit breaker trips, do not stop pushing indefinitely. The safer approach is to keep the last valid snapshot and continue pushing downstream, while marking the data as stale in the message, for example dataStale=true, so the frontend does not present an old price as a live one.

    Idempotency is also mandatory on the ingestion side. Use “symbol + source + sequence” as the idempotency key. Some sources resend or backfill data to guarantee delivery reliability; without deduplication on the receiving side, the same quote is counted multiple times, distorting volume, average price, and similar metrics. Note that deduplication state must be kept only within a bounded window, otherwise state grows without limit as symbol count and time increase.

    4. Validation and Cleaning: Four Rule Sets to Block Dirty Data

    The goal of validation is not “looks reasonable” but automatically executable rules that stop bad data. Four rule sets are recommended.

    Rule Set 1: Format and Completeness

    • Symbol, market, and currency must be non-empty.
    • Price precision must match the convention of that market.
    • Required timestamps must exist and be parseable.

    Rule Set 2: Range Relationships

    Price fields have strict constraints:

    ID Condition Explanation
    C1 price > 0 Price must be positive
    C2 high ≥ low The high must not be below the low
    C3 low ≤ open ≤ high The open should fall inside the day’s range
    C4 high ≥ max(open, price) The high should cover the highest price seen today
    C5 low ≤ min(open, price) The low should cover the lowest price seen today
    C6 abs(price − prevClose) / prevClose ≤ threshold Flag as suspicious when a single record exceeds the change threshold

    Note: the previous close belongs to the prior trading session and is normally outside the current day’s range. C4 and C5 must not include the previous close, otherwise every symbol that gaps up or down would be rejected.

    Validating the example record item by item:

    • C1: price = 282.1 > 0, pass.
    • C2: high = 285.1354 ≥ low = 275.36, pass.
    • C3: 275.36 ≤ open = 284.275 ≤ 285.1354, pass.
    • C4: max(open, price) = max(284.275, 282.1) = 284.275, and high = 285.1354 ≥ 284.275, pass.
    • C5: min(open, price) = 282.1, and low = 275.36 ≤ 282.1, pass.
    • C6: (282.1 - 265.29) / 265.29 ≈ 6.34%. Passes with a default threshold of 15%; for a low-volatility instrument with a stricter threshold, it may be rejected or routed to manual review.

    Also note: the example is only a partial snapshot. Full snapshot validation additionally needs volume, turnover, the traded prices at the high and low, the trading calendar, and currency precision; otherwise only basic validation is possible.

    Rule Set 3: Baseline and Time Checks

    • The previous close must be greater than zero.
    • The date relationship between the open and the last price must be explicit.
    • The quote time must not be materially ahead of the receive time. A quote time later than the receive time indicates a clock source problem or tampered data.
    • Price limits, circuit breakers, and other trading mechanisms affect the valid price range, so validation rules must adapt accordingly.

    Rule Set 4: State and Deduplication Checks

    • Maintain the highest received sequence per symbol and discard records whose sequence goes backwards.
    • Treat data whose quote time precedes the last processed result as out-of-order.
    • Process a message with a given sequence only once.

    Here is a validator skeleton:

    1. import java.math.BigDecimal;
    2. import java.math.RoundingMode;
    3. import java.util.Optional;
    4. import java.util.concurrent.ConcurrentHashMap;
    5. import java.util.concurrent.ConcurrentMap;
    6. public class QuoteGuard {
    7. private static final BigDecimal MAX_CHANGE_RATIO = new BigDecimal("0.15");
    8. private final ConcurrentMap<String, Long> lastSeqBySource = new ConcurrentHashMap<>();
    9. public Optional<QuoteUpdate> accept(QuoteUpdate q) {
    10. if (q.symbol() == null || q.symbol().isBlank()
    11. || q.price() == null
    12. || q.open() == null
    13. || q.high() == null
    14. || q.low() == null
    15. || q.prevClose() == null
    16. || q.prevClose().signum() <= 0
    17. || q.volume() < 0) {
    18. return Optional.empty();
    19. }
    20. String seqKey = q.symbol() + "@" + q.source();
    21. Long previous = lastSeqBySource.get(seqKey);
    22. if (previous != null && q.sourceSeq() <= previous) {
    23. return Optional.empty();
    24. }
    25. lastSeqBySource.put(seqKey, q.sourceSeq());
    26. if (q.eventTimeMs() > q.receiveTimeMs()) {
    27. return Optional.empty();
    28. }
    29. if (q.price().signum() <= 0
    30. || q.high().compareTo(q.low()) < 0
    31. || q.open().compareTo(q.low()) < 0
    32. || q.open().compareTo(q.high()) > 0
    33. || q.high().compareTo(q.open().max(q.price())) < 0
    34. || q.low().compareTo(q.open().min(q.price())) > 0) {
    35. return Optional.empty();
    36. }
    37. BigDecimal change = q.price()
    38. .subtract(q.prevClose())
    39. .abs()
    40. .divide(q.prevClose(), 6, RoundingMode.HALF_UP);
    41. if (change.compareTo(MAX_CHANGE_RATIO) > 0) {
    42. // Do not drop outright: route to a review queue for manual or
    43. // secondary rule confirmation before releasing
    44. return Optional.empty();
    45. }
    46. return Optional.of(q);
    47. }
    48. }

    In real production, sequence validation should use atomic operations or a centralized deduplication service, so concurrent paths cannot let duplicates through. Rejected data should not simply be dropped; handle it in tiers:

    • Format errors, sequence regression: count and drop.
    • Out-of-range prices, change beyond threshold: route to a review queue.
    • Source heartbeat timeout: alert and consider a primary/backup switch.

    5. Stream Computation: Out-of-Order Data, Incrementality, and Trading Sessions

    Network jitter and multi-source merging inevitably produce out-of-order data. Stream computation typically uses event time and watermarks to decide whether “data before a given point in time has essentially all arrived”. The processing logic:

    1. The watermark advances with time and allows a bounded amount of lateness.
    2. Late data within the allowed range triggers a recompute of the corresponding window.
    3. Data beyond the range goes to a side output stream for separate handling, or is dropped and counted.

    Tolerance must be set by business needs. Quote display can tolerate second-level error; statistics around critical periods such as the closing call auction need a longer tolerance window and a stricter recompute mechanism.

    Computation should be incremental rather than a full recompute. Last price, change percentage, and range can be derived directly from the latest quote:

    1. change = price - prevClose
    2. changeRatio = change / prevClose
    3. amplitude = (high - low) / prevClose

    Metrics such as average price and cumulative volume need state plus incremental updates. For a volume-weighted running average, maintain the state explicitly:

    1. class AvgState {
    2. long count = 0;
    3. long volume = 0;
    4. BigDecimal turnover = BigDecimal.ZERO;
    5. BigDecimal avgPrice = BigDecimal.ZERO;
    6. }

    On arrival:

    1. count += 1;
    2. volume += q.volume();
    3. turnover = turnover.add(q.price().multiply(BigDecimal.valueOf(q.volume())));
    4. avgPrice = volume == 0
    5. ? BigDecimal.ZERO
    6. : turnover.divide(BigDecimal.valueOf(volume), 4, RoundingMode.HALF_UP);

    On out-of-order rollback:

    1. count -= 1;
    2. volume -= q.volume();
    3. turnover = turnover.subtract(q.price().multiply(BigDecimal.valueOf(q.volume())));
    4. if (count <= 0 || volume <= 0) {
    5. count = 0;
    6. volume = 0;
    7. turnover = BigDecimal.ZERO;
    8. }
    9. avgPrice = volume == 0
    10. ? BigDecimal.ZERO
    11. : turnover.divide(BigDecimal.valueOf(volume), 4, RoundingMode.HALF_UP);

    The advantage of this design is that computational complexity is independent of history length and depends only on live throughput. When maintaining state, pair it with checkpoints for failure recovery, and ensure consistency between state updates and result output.

    Real-time computation must also distinguish continuous trading, call auctions, midday breaks and closures, and after-hours fixed-price trading. Otherwise two problems appear:

    1. During closures, stale prices are repeatedly used to recompute change percentages, making page values jump meaninglessly.
    2. If the previous close is not switched at the session boundary, an abnormal change appears the moment the market opens.

    Keep the trading calendar as independent base data, publish it to compute nodes by the “market + trading day” dimension, and carry the current session identifier with the quotes.

    Storage should also be tiered by temperature:

    Data type Retention Primary use Typical storage form
    Latest snapshot Current trading day Page display, API queries In-memory, low-latency store
    Tick or trade-by-trade detail Weeks to months Real-time computation, retrospective validation Time-series database
    Minute or daily aggregates Months to years Historical queries, batch analysis Columnar store or data warehouse
    Raw messages Archived per compliance requirements Audit, incident replay Object storage archive

    The tiering principle is to retain on demand and reduce precision layer by layer. Frequently accessed latest state lives in low-latency storage, history goes to a time-series database, older data is downsampled into columnar storage, and raw messages are archived periodically.

    6. Transport and Push: Batching and Back-Pressure on Long-Lived Connections

    Protocol choice depends on the scenario:

    Protocol Suitable scenario Characteristics
    WebSocket Interactive quote terminals, large screens Bidirectional; server can push proactively; heartbeat, reconnect, and auth must be handled manually
    SSE Quote panels that are mostly server-to-client HTTP-based, simple to implement, automatic reconnect, unsuitable for high-frequency bidirectional interaction
    Long or short polling Compatibility or low-frequency scenarios Simplest to implement, but timeliness is bounded by the polling interval

    Whatever protocol is used, define an upper bound on per-connection message frequency and enforce rate limiting at the gateway.

    Pushing record by record produces a flood of small packets when quotes update frequently, adding protocol header and system call overhead. The effective approach is server-side batch aggregation:

    • Merge messages for the same client over a 50–200 ms window.
    • When the same symbol updates multiple times inside the window, keep only the latest one.
    • When the send buffer approaches its threshold, prefer merging or dropping intermediate states so the latest price arrives first.
    • Disconnect and reconnect long-lived connections that stop consuming, to avoid unbounded memory growth.

    The window size is not a constant. Low-frequency quotes can use a longer window to cut overhead; high-frequency quotes need a shorter window to protect timeliness. Also set per-instance limits on memory, connections, and buffer size so a few connections cannot take down the gateway.

    Push services are usually deployed as multiple instances. A single client’s connection lands on only one of them, while compute nodes are spread across others. The solution is to write compute-layer output into a publish/subscribe message queue, then have each push instance filter by client subscription before sending. Two points matter here:

    1. Efficient subscription indexing: build a “symbol to set of connections” index.
    2. Locality: schedule connections subscribing to the same symbol onto the same instance where possible, reducing cross-node fan-out.

    After reconnecting, a client cannot simply resume the stream, or updates from the outage window are lost. The correct sequence:

    1. The client subscribes with the last received quote time and sequence.
    2. The server first backfills the latest snapshot.
    3. Then it resumes the real-time increments.
    4. The client deduplicates by sequence and reconciles by quote time.

    Below is a corrected batch-push sketch. It avoids losing the latest snapshot when there are no subscribers, avoids writing unsubscribed symbols into memory indefinitely, and avoids undeclared logging and hand-built JSON:

    1. import com.fasterxml.jackson.core.JsonProcessingException;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import org.slf4j.Logger;
    4. import org.slf4j.LoggerFactory;
    5. import java.util.LinkedHashMap;
    6. import java.util.Map;
    7. import java.util.Set;
    8. import java.util.concurrent.ConcurrentHashMap;
    9. import java.util.concurrent.ConcurrentMap;
    10. import java.util.concurrent.Executors;
    11. import java.util.concurrent.ScheduledExecutorService;
    12. import java.util.concurrent.TimeUnit;
    13. public class QuoteBroadcaster {
    14. private static final Logger log = LoggerFactory.getLogger(QuoteBroadcaster.class);
    15. private static final ObjectMapper JSON = new ObjectMapper();
    16. public interface Session {
    17. void send(String message);
    18. }
    19. private final ConcurrentMap<String, Set<Session>> index = new ConcurrentHashMap<>();
    20. private final ConcurrentMap<String, QuoteUpdate> buffer = new ConcurrentHashMap<>();
    21. private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
    22. Thread t = new Thread(r, "quote-broadcast");
    23. t.setDaemon(true);
    24. return t;
    25. });
    26. public void subscribe(String symbol, Session session) {
    27. QuoteUpdate snapshot = buffer.get(symbol);
    28. if (snapshot != null) {
    29. try {
    30. session.send(buildMessage(symbol, snapshot, true));
    31. } catch (RuntimeException e) {
    32. log.warn("send snapshot failed, symbol={}", symbol, e);
    33. return;
    34. }
    35. }
    36. // If no snapshot is in the buffer, fetch the latest snapshot from
    37. // storage first, then join the real-time channel
    38. index.computeIfAbsent(symbol, k -> ConcurrentHashMap.newKeySet()).add(session);
    39. }
    40. public void unsubscribe(String symbol, Session session) {
    41. Set<Session> sessions = index.get(symbol);
    42. if (sessions != null) {
    43. sessions.remove(session);
    44. if (sessions.isEmpty()) {
    45. index.compute(symbol, (k, v) -> v == null || v.isEmpty() ? null : v);
    46. buffer.remove(symbol);
    47. }
    48. }
    49. }
    50. public void onQuote(QuoteUpdate q) {
    51. Set<Session> sessions = index.get(q.symbol());
    52. if (sessions == null || sessions.isEmpty()) {
    53. // Drop symbols with no subscribers to avoid a continuous memory leak
    54. buffer.remove(q.symbol());
    55. return;
    56. }
    57. buffer.put(q.symbol(), q);
    58. }
    59. public void start(long windowMs) {
    60. scheduler.scheduleAtFixedRate(this::flush, windowMs, windowMs, TimeUnit.MILLISECONDS);
    61. }
    62. private void flush() {
    63. for (Map.Entry<String, Set<Session>> entry : index.entrySet()) {
    64. Set<Session> sessions = entry.getValue();
    65. if (sessions == null || sessions.isEmpty()) {
    66. buffer.remove(entry.getKey());
    67. continue;
    68. }
    69. QuoteUpdate latest = buffer.remove(entry.getKey());
    70. if (latest == null) {
    71. continue;
    72. }
    73. String message = buildMessage(entry.getKey(), latest, false);
    74. for (Session session : sessions) {
    75. try {
    76. session.send(message);
    77. } catch (RuntimeException e) {
    78. sessions.remove(session);
    79. log.warn("send failed, symbol={}, drop session", entry.getKey(), e);
    80. }
    81. }
    82. }
    83. }
    84. private String buildMessage(String symbol, QuoteUpdate q, boolean snapshot) {
    85. Map<String, Object> message = new LinkedHashMap<>();
    86. message.put("symbol", symbol);
    87. message.put("snapshot", snapshot);
    88. message.put("price", q.price().toPlainString());
    89. message.put("eventTime", q.eventTimeMs());
    90. try {
    91. return JSON.writeValueAsString(message);
    92. } catch (JsonProcessingException e) {
    93. throw new IllegalStateException("build quote message failed", e);
    94. }
    95. }
    96. }

    7. Observability and Security: How Do You Detect High Latency?

    Observability for a market data system should be organized around “is it fresh, is it accurate, is it reachable”.

    Category Key metric What it tells you
    Timeliness Receive time minus quote time End-to-end latency of the data path
    Timeliness Heartbeat interval and time-without-updates per source Early detection of source anomalies
    Completeness Dedup drops, out-of-order drops, validation rejections Classified counts that localize the problem source
    Completeness Price differences between primary and backup Detects data divergence
    Performance Message queue backlog, processing latency Whether the compute layer is the bottleneck
    Performance Gateway active connections, memory, send failure rate, client reconnect rate Long-lived connection stability
    Business Count of abnormal-change and out-of-range price alerts Data quality level

    For alerting, use multi-level thresholds: record the trend when latency rises slightly; notify on-call staff when the tolerance limit is exceeded; switch primary and backup automatically when a source stops updating for a long time.

    For tracing, one quote often crosses ingestion, validation, computation, and push services. Carry a unified message identifier through the pipeline, such as “symbol + source + sequence”, and have each service record its processing time in logs. Aggregating logs by that identifier reconstructs the full path after the fact.

    Security should include at least:

    • Authentication and authorization: complete identity verification when the long-lived connection is established, and check data permissions on subscribe.
    • Transport security: enable encryption end to end, so quote data cannot be intercepted or tampered with.
    • Rate limiting and isolation: cap the number of subscribed symbols and the message rate per tenant, so a single client cannot take down the gateway.
    • Data compliance: the permitted use, display, and redistribution of market data is usually governed by upstream data agreements, so build least privilege and access auditing into the system design.

    8. High Availability: Which Risks Must Be Rehearsed in Advance?

    The availability of a real-time market data system ultimately shows up as “accurate data, fast arrival, stable connections”. Every component that can cause an outage needs a predefined response.

    Risk Typical symptom Response
    Source failure Quotes stop updating Multi-source redundancy, automatic switchover, heartbeat detection
    Network jitter Batches out of order, brief disconnects Watermark tolerance, backfill, client reconnect
    Traffic peak Connection surge at the open, the close, or major events Elastic gateway scaling, sharding by symbol, batch aggregation
    Data anomaly Out-of-range prices, abnormal changes Multi-level validation, anomaly isolation, manual review
    Node failure Some push instances unavailable Keep gateway business logic stateless; externalize session state or make it quickly rebuildable
    Resource exhaustion Connections or memory near the limit Per-instance connection and memory caps, graceful drain, reconnect instruction to clients

    In public markets, many symbols update in the same window, and traffic is especially concentrated near the open and the close. This requires the push path to scale horizontally while avoiding too many connections on a single instance. When an instance goes offline, send clients an explicit reconnect instruction and drain traffic through the load balancer. For drills, inject failures regularly: forcibly disconnect a data source, shut down some push instances, or introduce network jitter, then verify that primary/backup switchover and client reconnection actually work.

    9. Troubleshooting Quick Reference

    Symptom What to check first Action
    Page price jumps Sequence regression, lateness beyond the window, snapshot misalignment Check the idempotency key, the watermark, and reconnect backfill logic
    Validation false positives before the call auction Trading calendar, current session, previous close, change threshold Separate trading sessions; configure thresholds per instrument
    Duplicate consumption distorts average price Whether the idempotency key works, whether the dedup window is too short Deduplicate by symbol, source, and sequence with a bounded window
    Source heartbeat is healthy but no updates arrive Subscriptions, rate limiting, circuit breaking, stale-data marking Check the ingestion path and push filter conditions
    Push gateway memory keeps growing Dead connections, buffer buildup, writes for unsubscribed symbols Reap dead sessions and drop symbols with no subscribers immediately

    10. FAQ

    How do I troubleshoot high real-time quote latency?

    First check the difference between receive time and quote time at ingestion, then the compute-layer queue backlog, then push gateway send latency and the client network. If ingestion latency is normal but push latency is high, focus on the batch window, the buffer, connection count, and client consumption speed.

    How do I avoid losing quotes on reconnect?

    The client reconnects with the last quote time and sequence, the server first backfills the latest snapshot and then resumes real-time increments. The client deduplicates by sequence and keeps the newest data by quote time.

    What should I do about validation false positives?

    Start with the rule that fired. In gap scenarios, the usual mistake is including the previous close in the current day’s range constraints; for price limits, circuit breakers, and call auctions, adjust by trading calendar and per-instrument thresholds. Anomalous data belongs in a review queue rather than being dropped.

    Why can’t I use floating point for prices?

    Binary floating point introduces precision errors that affect change percentages, average prices, and reconciliation. Use BigDecimal or an integer representation, and apply a single rounding policy.

    How do I switch between multiple sources?

    Use the primary while it is healthy. Switch to the backup when the primary misses a heartbeat or stops updating for a long time. After the primary recovers, switch back only after an observation period to avoid flapping.

    11. Launch Checklist

    • Is the quote model split into static metadata and dynamic quote updates?
    • Does it include quote time, receive time, source, and sequence?
    • Are prices uniformly represented with high-precision decimals or integers?
    • Are range validation and change thresholds configured per instrument?
    • Is the previous close kept out of the current day’s range checks?
    • Is there a separate review and alerting channel for anomalous data?
    • Is deduplication state kept only within a bounded window?
    • Does stream computation handle lateness tolerance and failure recovery?
    • Does push do window aggregation, back-pressure control, and dead-connection cleanup?
    • Are symbols with no subscribers dropped or expired immediately?
    • Can a reconnecting client get a snapshot first and then resume increments?
    • Are latency percentiles, queue backlog, connection failure rate, and memory limits all monitored?
    • Have multi-source and multi-instance failures been rehearsed regularly?

    Implementing these details across design, development, and operations yields a real-time market data service with accurate data, controlled latency, and stable operation, providing a reliable foundation for quote display, quantitative analysis, and risk control on top.