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 app | Source | Market-data time, UTC | Last price | Decision |
|---|---|---|---|---|
| First | WebSocket | 14:30:00.500 | 180.25 | Show 180.25 |
| Second | REST | 14:30:00.000 | 180.10 | Keep 180.25 |
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.


Top comments (2)
Keying on (symbol, session) and comparing event time is the right gate, and the
conflictreturn on equal timestamps with different prices is the detail most versions of this leave out.The same race runs in payments, where a webhook and a poll both report a payment's state and the poll can answer with a state older than the webhook already delivered. One asymmetry is worth carrying over, because it is why the quote version is the easier one. A quote card holds a value, so dropping the older message is always safe. A payment status is a lifecycle, and newest-wins on timestamps alone will walk a settled payment back to pending the first time two emitters disagree about the clock. So the gate wants event time and a legality check on the transition, and a transition that is newer but illegal is a clock problem to alert on rather than a state to apply.
Which is the limit on your gate too.
event_msordering assumes one clock, or synchronised ones. REST and the stream are usually two emitters, and if their skew is larger than the gap between events then you are ordering by skew. The fix is a sequence number from the source rather than a timestamp, and most market data APIs will not give you one per symbol. Worth saying out loud in the post, because a reader who ships your gate and later sees a backward tick will go looking in their own code first.Thanks, Arun. The payments example makes the distinction clear: a newer timestamp doesn't make an invalid state transition valid.
I should have made the assumption behind event_ms explicit. The comparison only works when the REST snapshot and WebSocket updates use comparable event timestamps. If the provider documents a sequence or version that spans both, I'd use that instead. Without a shared ordering signal, I wouldn't let a snapshot overwrite a live quote just because its timestamp is larger. I'd keep the live quote on screen, flag the ordering as uncertain, and resync.