Building a Real-Time US Stock Quote System: From Data Ingestion to Monitoring and Alerting

    This article covers the design of a real-time US stock quote system. It explains the key quote fields, multi-source data ingestion with failover, data cleaning and validation, time-series storage options, real-time metric calculation, front-end display, data licensing, and monitoring and alerting. Readers will see how each stage of the pipeline works and what to check at each step.

    Starting with a Sample Record

    The following is a sample record used to explain the meaning of each field. The data is fictional, does not correspond to any real company or security, and does not constitute investment advice.

    Symbol: EXAMPLE; Market: US stocks; Currency: USD; Last price: 100.00; Previous close: 101.00; Change: -1.00; Change rate: -0.99%; Exchange timestamp: 2026-11-24 13:30:00 UTC.

    This record looks like a set of numbers, but it sits on top of a full pipeline that covers data collection, cleaning, storage, calculation, and display. Developers need to understand the business meaning of each field before they can judge whether the system is reliable.

    1. Breaking Down Quote Fields

    A standard quote snapshot usually contains three types of information.

    Identifier fields determine which security a quote belongs to. For US stocks, the ticker symbol is the core identifier. The market identifier distinguishes exchanges and their trading rules. US, Hong Kong, and A-share markets differ in trading hours, daily price limits, and settlement rules. These differences affect collection frequency and calculation logic.

    Price fields include the last price, the price change, and the change rate. The change rate equals (last price minus previous close) divided by previous close, multiplied by 100%. This metric reflects short-term movement, but it depends on an accurate previous close.

    Timestamp fields record when a quote was generated, to the second or millisecond. They are the basis for judging data freshness and calculating latency. The system should store timestamps in UTC and convert them to the user’s time zone for display.

    2. Data Ingestion: Multi-Source Access and Failover

    A single data source can suffer from delays, outages, or bad data. Common sources include official exchange data feeds, APIs from commercial data providers, and public financial data platforms. Field names, precision, and time formats often differ between sources, so define a unified data model first:

    1. from dataclasses import dataclass
    2. @dataclass(frozen=True)
    3. class QuoteData:
    4. symbol: str # Security symbol
    5. market: str # Market identifier, e.g. "US"
    6. price: float # Latest price
    7. prev_close: float # Previous close price
    8. exchange_ts: int # Exchange timestamp in UTC milliseconds
    9. source: str # Data source identifier
    10. session: str # Trading session: regular, pre, or post

    Failover works best with a primary-plus-backup strategy, with configurable thresholds. The example thresholds below are illustrative. Actual values should be adjusted based on each provider’s service level agreement and trading sessions:

    • If the primary source times out continuously for more than 2 seconds, switch to the backup source. Continuous timeouts mean requests return no valid data within the threshold.
    • After a failed request, retry with exponential backoff. For example, wait 100 milliseconds for the first retry and double the wait each time. Set a maximum retry count.
    • Rate-limit calls to external interfaces, commonly with a token bucket algorithm. Exceeding a quota can cause the provider to suspend service, so set the limit below the provider’s cap.
    • Log every switch, including the time, the reason, and the sources before and after the switch, for later analysis.

    3. Data Cleaning and Validation

    Raw quotes may have missing values, out-of-order records, duplicates, and misaligned fields. The cleaning process should run before data is stored, and each type of anomaly needs a clear handling rule.

    Price validity checks require prices to be greater than zero. A single price jump also needs a limit, for example 5%. Data that exceeds the limit is not discarded immediately. It waits for confirmation from the next update. If two consecutive updates deviate, the data goes to a manual review queue.

    Out-of-order records are sorted by exchange timestamp. If a record arrives after the waiting window, discard it and log the event.

    Duplicates are identified with a deduplication key. The recommended key combines symbol, data source, exchange timestamp, and sequence number. Records with the same key keep only one copy.

    Field misalignment means the field count or types do not match the model. Such records go straight to an exception queue and do not enter formal storage.

    Multi-source data can be cross-checked. When prices from two sources differ by less than 0.01 USD, treat them as consistent. If one source consistently deviates from the others, reduce its weight and trigger a quality check for that source.

    4. Time-Series Storage Selection

    Quote data is high-throughput time-series data. The table below compares three storage options.

    Dimension Time-series database Relational database Object storage
    Write throughput High, optimized for batch writes keyed by timestamp Performance drops under high-concurrency writes Not suitable for real-time writes
    Compression ratio High Medium High, but no real-time queries
    Retention policy Supports automatic expiration and downsampling Requires custom cleanup jobs Managed through lifecycle rules
    Aggregation queries Supports continuous aggregation with fast queries Slow for long-range aggregation No direct query support
    Operating cost Medium, requires dedicated maintenance Lower, with mature team experience Low

    Mixed storage is recommended. Store reference data, such as security master data and trading calendars, in a relational database. Store tick-level snapshots and minute bars in a time-series database. Archive historical data past its retention period to object storage.

    Retention settings can follow this plan. Keep raw snapshots for 30 days for auditing and short-term analysis. Keep 1-minute bars for 6 months for medium-term trend analysis. Keep daily bars long term for backtesting. The time-series database can periodically aggregate high-precision data into lower-precision data to reduce storage costs.

    5. Real-Time Calculation and Derived Metrics

    Calculating the change rate requires three prerequisites.

    The first is adjusting the previous close for corporate actions. If a stock paid dividends or split before the previous trading day, the raw previous close cannot be used directly. It must be adjusted for those actions. Otherwise, the change rate will be distorted.

    The second is the trading session. Volume and liquidity differ considerably between pre-market, regular, and after-hours sessions. Snapshots should record the session type so that pre-market moves are not analyzed as normal trading activity.

    The third is the time zone and trading calendar. The system stores data in UTC. To determine trading sessions and trading days, convert timestamps to the exchange’s local time. For US stocks, that is US Eastern Time, and daylight saving time must be handled correctly.

    Technical indicators can be computed with a streaming engine such as Kafka Streams or Flink. Below is an example of a simple moving average. The caller must ensure that input prices are sorted in ascending time order and belong to the same security, the same adjustment basis, and the same trading session:

    1. from typing import Optional, Sequence
    2. def calculate_sma(prices: Sequence[float], window: int = 5) -> Optional[float]:
    3. if window <= 0:
    4. raise ValueError("window must be a positive integer")
    5. if len(prices) < window:
    6. return None
    7. recent = prices[-window:]
    8. if any(p is None or p <= 0 for p in recent):
    9. return None
    10. return round(sum(recent) / window, 2)

    6. Visualization and Front-End Display

    Quote pages need near-real-time refresh. WebSocket suits high-frequency push and supports two-way communication. Server-Sent Events (SSE) are simpler to implement, and browsers reconnect automatically, which makes them a good fit for one-way push.

    Color conventions for price changes vary by region. US market interfaces typically use green for gains and red for losses. Users in mainland China typically use red for gains and green for losses. Make the color scheme a configurable option, such as color_scheme = "up_green" or "up_red", and let users set it per market or per user.

    When historical