When a REST Snapshot Arrives After a WebSocket Stock Quote

TickDB Research ·

Editorial cover: contrasting paths for a fast streaming quote and a delayed snapshot

A Python quote card can move backward even when both data requests succeed. This happens when a WebSocket update reaches the app before an older REST snapshot finishes. Normalize both responses to the same kind of price, key the result by symbol and trading session, and replace the displayed value only when the incoming market-data timestamp is newer.

Use this rule for a display of the latest price, not for replaying every trade. An older message can still matter in a trade archive; it should not roll a quote card backward.

Why the newest response can contain the older price

Suppose a WebSocket quote for AAPL arrives with data time 14:30:00.500 UTC and price 180.25. REST finishes later, but its data time is 14:30:00.000 and its price is 180.10. If both handlers simply assign to the same card, the card changes from 180.25 to 180.10 without a new market event. Comparing data timestamps keeps 180.25.

The prices and times below are synthetic, not observed AAPL trades or API latency measurements.

Order in the appSourceMarket-data time, UTCLast priceDecision
FirstWebSocket14:30:00.500180.25Show 180.25
SecondREST14:30:00.000180.10Keep 180.25

Synthetic timeline: newer WebSocket update accepted, older REST snapshot ignored

Record receive time separately. It's useful for diagnosing a slow request or a quiet stream, but it must not decide which price is newer.

Align the fields before comparing times

TickDB's REST Ticker Snapshot documents a last_price and a millisecond timestamp. Its extended-hours quote objects have their own last_done and timestamp. The WebSocket ticker schema carries last_price and timestamp; its U.S. stock examples use trade_session to identify pre_market, post_market, and overnight. Normalize documented regular and extended payloads to explicit session keys before comparing them. Don't let a newer extended-hours timestamp silently replace the regular-session price.

Compare last trade with last trade. If the card shows bid and ask too, define how those fields update instead of replacing everything with a partial message. Validate the application response, symbol and fields even after HTTP 200. Flag invalid timestamps and unrecognized session labels instead of substituting the app's receive time.

A minimal gate you can test without an account

The Python gate consumes already-normalized observations. It preserves the old price and reports a conflict when the same timestamp has two different prices. That's a display policy: equal timestamps do not prove that events are duplicates. For trade archives, rely on documented event identity, sequencing, or correction semantics instead.

from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)
class Quote:
    symbol: str
    session: str
    event_ms: int
    price: Decimal
    source: str

class QuoteGate:
    def __init__(self):
        self.latest = {}

    def accept(self, q):
        key = (q.symbol, q.session)
        old = self.latest.get(key)
        if old is None or q.event_ms > old.event_ms:
            self.latest[key] = q
            return "accepted"
        if q.event_ms < old.event_ms:
            return "older"
        return "duplicate" if q.price == old.price else "conflict"

if __name__ == "__main__":
    t = 1795185000000  # Synthetic event-time base in milliseconds.
    gate = QuoteGate()
    cases = [
        ("regular", 500, "180.25", "websocket", "accepted"),
        ("regular", 0, "180.10", "rest", "older"),
        ("regular", 500, "180.25", "websocket", "duplicate"),
        ("regular", 500, "180.26", "websocket", "conflict"),
        ("pre_market", -1000, "179.90", "rest", "accepted"),
        ("regular", 800, "180.30", "rest", "accepted"),
    ]
    for session, offset, price, source, expected in cases:
        action = gate.accept(Quote("AAPL.US", session, t + offset, Decimal(price), source))
        assert action == expected, (source, offset, action)
        print(source, session, offset, price, action)
    assert gate.latest["AAPL.US", "regular"].price == Decimal("180.30")
    assert gate.latest["AAPL.US", "pre_market"].price == Decimal("179.90")

The local fixture checks six cases: first update, older REST response, repeat, equal-time conflict, separate pre-market price, and genuinely newer REST snapshot. All six assertions passed. Two additional assertions verify that the regular and pre-market values remain separate. No live feed, latency, or reconnect replay was tested.

In an async app, send both adapters' observations to one consumer queue, or put the comparison and write inside one lock. Otherwise both handlers can read the same old value and the slower handler can still win. A valid REST price can seed the display if the stream hasn't delivered one yet; the same gate handles either arrival order.

On reconnect, subscribe again as the provider requires. TickDB's current WebSocket guide documents resubscription and another initial snapshot for a full-market subscription. That snapshot can refresh the current view; it doesn't prove that all missed events were replayed. Track freshness separately from the connected state, using a threshold appropriate to the selected session and workload.

To accept this change, deliberately delay the older REST response and confirm neither the displayed price nor its data time rolls back. Also verify that equal-time conflicts are visible and extended-hours quotes can't overwrite the regular-session card.

Technical references checked: TickDB Ticker Snapshot, WebSocket Ticker, and WebSocket Best Practices. Written for TickDB Research. The merge policy also applies to other feeds exposing comparable timestamps and prices.

7 markets · 42,687 symbols

US stocks
14,386
Hong Kong market
3,353
China stocks, ETFs & bonds
7,576
Forex & metals
1,228
Indices
13,960
Futures
1,172
Crypto
1,012
11/23/2026

Explore related data tools

Related articles

Build a Python Stock Quote Snapshot with Explicit Missing-Data States

A Python stock API response needs more than a successful HTTP request before it can become a useful quote snapshot. Check the response envelope, match returned symbols to the requested list, and preserve missing fields instead of replacing them with zero. The documented TickDB ticker schema supplies the request and required fields; a defensive parser separates absent, null, blank, invalid, and numeric values without claiming that a snapshot proves freshness.

TickDB Research ·

Choose a Stock API by Testing Disconnect Recovery, Not Just Streaming Speed

A stock API can reconnect quickly while leaving an application with incomplete subscriptions or an unexplained gap in event history. Choose it by testing when data becomes usable again, not merely when the socket opens. A fresh snapshot can restore current state; only a documented replay or backfill mechanism can establish the required event continuity. The acceptance test below separates those outcomes and includes a small, locally tested recovery gate.

TickDB Research ·

Choose a US Stocks API That Keeps Extended Hours Data Distinct

A US stocks API can return a valid price while leaving an extended-hours screen misleading. For a product that shows pre-market, post-market or overnight activity, choose a feed whose coverage and session semantics you can verify, then keep each observation tied to its session and timestamp. TickDB documents separate extended-session snapshot objects; Alpaca documents separate stock feeds. Those are different integration choices, and neither removes the need to test missing data and session transitions.

TickDB Research ·

Choose a Stock API by Testing Requirements Before Comparing Price

A stock API can return valid JSON and still be unsuitable for your application. Choose candidates that meet your required data coverage, permitted use and operating capacity, then compare their total cost under the same workload. Alpaca’s documented IEX and SIP feed distinction shows why matching ticker symbols is not enough. A small acceptance test, with unresolved requirements kept visible, produces a more defensible shortlist than a feature count.

TickDB Research ·

Stock API Watchlists Can Share Requests Without Hiding Stale Prices

A stock watchlist can exhaust an API budget even when every user follows the same symbols. Where data permissions allow it, batching those symbols and sharing retrieval across viewers reduces duplicate upstream requests while preserving each record's timestamp. In a hypothetical case with 20 identical 120-symbol watchlists, batches of 50, and a five-second polling interval, independent polling needs 720 requests per minute; one shared collector needs 36, before retries and other traffic.

TickDB Research ·