A WebSocket connection can look perfectly healthy right up to the moment the process is restarted. The socket closes, an exception is raised, or a deployment replaces the container. Seconds later, the application reconnects—but the market-data feed may have moved forward while the program was offline.
The real challenge is therefore not reconnecting. It is preserving enough state to answer three questions:
- Which event was the last one processed?
- Which events have been received but not durably published?
- Can the missing interval be replayed, and how will duplicates be handled?
A reliable design separates these concerns into a local durable buffer, a checkpoint, an idempotent publishing path, and—when the upstream provider supports it—a resume or replay mechanism.
The core problem: “last received” is not a safe checkpoint
A naive implementation might store the latest trade timestamp in memory:
last_event_time = None
async for message in websocket:
event = parse(message)
last_event_time = event.timestamp
process(event)
This fails in several ways:
- The process may terminate before the timestamp reaches disk.
- A WebSocket may deliver duplicate messages.
- Some feeds may deliver events out of order.
- A reconnect may silently produce a gap.
- A timestamp cannot necessarily be used to resume a subscription.
- Advancing the checkpoint after an isolated event can hide an earlier missing event.
A checkpoint should therefore represent a contiguous, verified position in the upstream event stream, not merely the timestamp of the most recently observed message.
A useful checkpoint contains more than one field:
source
stream
stream_epoch
last_contiguous_sequence
resume_cursor
last_event_time
checkpoint_version
updated_at
The exact fields depend on the provider. Some venues expose numeric sequence numbers; others provide an opaque cursor. If neither is available, reliable gap detection and exact replay may be impossible.
A layered durability model
A robust ingestion architecture usually has four layers:
WebSocket
│
▼
Parser and validator
│
▼
SQLite transaction
├── buffered event
└── checkpoint update
│
▼
Publishing worker
│
▼
TickDB or another long-term market-data store
Each layer has a distinct responsibility.
1. WebSocket layer
The WebSocket provides live transport. It should not be treated as the system of record.
Depending on the provider, the stream may provide:
- A monotonically increasing sequence number
- An opaque resume cursor
- Periodic sequence resets
- Heartbeats or snapshots
- Historical replay
- At-least-once delivery
The client must determine which of these guarantees are actually available.
2. Durable local buffer
A small embedded database such as SQLite can serve as a write-ahead log and transactional outbox. It provides a simple way to atomically persist both:
- The newly received event
- The updated checkpoint
This local buffer is not intended to replace a long-term analytical database. It exists to close the crash window between receiving an event and publishing it elsewhere.
3. Checkpoint layer
The checkpoint records the last event that can safely be treated as processed. Advancing it is a durability operation, not an in-memory assignment.
4. Long-term store
A time-series database such as TickDB can retain normalized events for historical queries, signal research, replay, and downstream analytics. The local SQLite journal remains the short-lived transactional staging area.
The correct commit order
Consider this sequence:
- A WebSocket message arrives.
- The client parses and validates it.
- The client inserts the event into SQLite.
- The same transaction advances the checkpoint.
- A worker publishes the event to TickDB.
- The worker records successful publication in SQLite.
This order gives the process useful crash semantics.
Crash before the SQLite transaction commits
The event was received but is not durably stored. Recovery depends on upstream replay. No local mechanism can protect an event that was never committed to disk.
Crash after the SQLite commit but before publication
The event remains in the SQLite outbox. On restart, the publisher scans pending rows and sends them to TickDB.
Crash after publication but before the local “published” marker
The event may be published twice. This is acceptable only if ingestion is idempotent. The event therefore needs a stable ingestion identifier.
The important principle is:
The checkpoint must never advance beyond an event that exists in durable local storage.
Persisting an event and checkpoint atomically
The following Python example illustrates the transaction pattern. It assumes the upstream stream exposes a numeric source_seq.
import hashlib
import json
import sqlite3
import time
from dataclasses import dataclass
from typing import Optional
@dataclass
class MarketEvent:
source: str
stream: str
stream_epoch: str
source_seq: int
resume_cursor: Optional[str]
event_ts: int
payload: bytes
class DurableEventBuffer:
def __init__(self, path: str = "ingestion.db"):
self.db = sqlite3.connect(path, isolation_level=None)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA journal_mode = WAL")
self.db.execute("PRAGMA synchronous = FULL")
self.db.execute("PRAGMA busy_timeout = 5000")
self.db.executescript(
"""
CREATE TABLE IF NOT EXISTS buffered_events (
event_id TEXT PRIMARY KEY,
source TEXT NOT NULL,
stream TEXT NOT NULL,
stream_epoch TEXT NOT NULL,
source_seq INTEGER,
resume_cursor TEXT,
event_ts INTEGER NOT NULL,
payload BLOB NOT NULL,
payload_hash TEXT NOT NULL,
received_at INTEGER NOT NULL,
published_at INTEGER,
UNIQUE (
source,
stream,
stream_epoch,
source_seq
)
);
CREATE INDEX IF NOT EXISTS idx_buffered_pending
ON buffered_events(published_at, source_seq);
CREATE TABLE IF NOT EXISTS checkpoints (
source TEXT NOT NULL,
stream TEXT NOT NULL,
stream_epoch TEXT NOT NULL,
last_seq INTEGER,
resume_cursor TEXT,
last_event_ts INTEGER,
updated_at INTEGER NOT NULL,
PRIMARY KEY (source, stream, stream_epoch)
);
"""
)
@staticmethod
def event_id(event: MarketEvent, payload_hash: str) -> str:
identity = (
f"{event.source}|{event.stream}|"
f"{event.stream_epoch}|{event.source_seq}"
)
return hashlib.sha256(identity.encode("utf-8")).hexdigest()
def persist(self, event: MarketEvent) -> str:
payload_hash = hashlib.sha256(event.payload).hexdigest()
event_id = self.event_id(event, payload_hash)
received_at = int(time.time() * 1_000_000_000)
self.db.execute("BEGIN IMMEDIATE")
try:
checkpoint = self.db.execute(
"""
SELECT last_seq
FROM checkpoints
WHERE source = ?
AND stream = ?
AND stream_epoch = ?
""",
(event.source, event.stream, event.stream_epoch),
).fetchone()
last_seq = checkpoint["last_seq"] if checkpoint else None
if last_seq is None:
is_contiguous = True
elif event.source_seq <= last_seq:
is_contiguous = False
else:
is_contiguous = event.source_seq == last_seq + 1
cursor = self.db.execute(
"""
INSERT OR IGNORE INTO buffered_events (
event_id,
source,
stream,
stream_epoch,
source_seq,
resume_cursor,
event_ts,
payload,
payload_hash,
received_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
event_id,
event.source,
event.stream,
event.stream_epoch,
event.source_seq,
event.resume_cursor,
event.event_ts,
event.payload,
payload_hash,
received_at,
),
)
# Advance the checkpoint only after the event row exists,
# and only when the sequence is contiguous.
if cursor.rowcount == 1 and is_contiguous:
self.db.execute(
"""
INSERT INTO checkpoints (
source,
stream,
stream_epoch,
last_seq,
resume_cursor,
last_event_ts,
updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(source, stream, stream_epoch)
DO UPDATE SET
last_seq = excluded.last_seq,
resume_cursor = excluded.resume_cursor,
last_event_ts = excluded.last_event_ts,
updated_at = excluded.updated_at
""",
(
event.source,
event.stream,
event.stream_epoch,
event.source_seq,
event.resume_cursor,
event.event_ts,
received_at,
),
)
self.db.execute("COMMIT")
return event_id
except Exception:
self.db.execute("ROLLBACK")
raise
def checkpoint(self, source: str, stream: str, epoch: str):
return self.db.execute(
"""
SELECT *
FROM checkpoints
WHERE source = ?
AND stream = ?
AND stream_epoch = ?
""",
(source, stream, epoch),
).fetchone()
def pending_events(self, limit: int = 1000):
return self.db.execute(
"""
SELECT *
FROM buffered_events
WHERE published_at IS NULL
ORDER BY source_seq
LIMIT ?
""",
(limit,),
).fetchall()
def mark_published(self, event_id: str):
self.db.execute(
"""
UPDATE buffered_events
SET published_at = ?
WHERE event_id = ?
""",
(int(time.time() * 1_000_000_000), event_id),
)
Notice the gap-handling rule. If sequence 102 arrives after checkpoint 100, the event is retained, but the checkpoint remains at 100. Sequence 101 is still considered missing.
Simply recording 102 as the latest event would incorrectly turn an observable gap into apparent continuity.
SQLite durability settings
The configuration in the example is intentionally conservative:
PRAGMA journal_mode = WAL;
PRAGMA synchronous = FULL;
PRAGMA busy_timeout = 5000;
WAL allows readers to continue while a writer is active. synchronous = FULL reduces the chance that a committed transaction is lost during an operating-system or hardware failure, at the cost of additional I/O.
NORMAL is often adequate for workloads where the upstream stream can replay a small loss window. If the upstream source cannot replay events, stronger local durability is more important than raw throughput.
It is also worth considering:
- Whether a separate process publishes events while the WebSocket process writes to SQLite
- Lock contention between the writer and publisher
- Whether the database is on a persistent disk rather than an ephemeral container filesystem
- Retention of published rows so the buffer does not grow indefinitely
Publishing to TickDB idempotently
A publisher should read pending events from SQLite and insert them into TickDB using a stable identifier. If the process crashes after TickDB commits the insert but before SQLite records published_at, the restart will retry the same event.
The retry must therefore be safe.
One possible TickDB table design is:
CREATE TABLE market_events (
source LowCardinality(String),
stream LowCardinality(String),
instrument LowCardinality(String),
event_time DateTime64(3, 'UTC'),
source_seq UInt64,
event_ts DateTime64(3, 'UTC'),
payload String,
payload_hash FixedString(64),
ingestion_id String,
version UInt64,
ingested_at DateTime64(3, 'UTC')
)
ENGINE = ReplacingMergeTree(version)
ORDER BY (
source,
stream,
instrument,
event_time,
source_seq,
ingestion_id
);
The exact DDL and ingestion method should be checked against the deployed TickDB version and access model. The architectural requirement is that ingestion_id remains identical across retries.
The publisher can be expressed as:
class TickDBPublisher:
def __init__(self, buffer, client, table="market_events"):
self.buffer = buffer
self.client = client
self.table = table
def publish_pending(self):
for row in self.buffer.pending_events():
document = {
"source": row["source"],
"stream": row["stream"],
"instrument": "resolved-during-normalization",
"event_time": row["event_ts"],
"source_seq": row["source_seq"],
"event_ts": row["event_ts"],
"payload": row["payload"].decode("utf-8"),
"payload_hash": row["payload_hash"],
"ingestion_id": row["event_id"],
"version": 1,
"ingested_at": row["received_at"],
}
# Use the TickDB client or HTTP interface available in the
# deployment. This call must use the same ingestion_id on retry.
self.client.insert_json_each_row(self.table, document)
# This update may execute after a crash even though TickDB
# already contains the event. The stable ingestion_id makes
# that retry harmless.
self.buffer.mark_published(row["event_id"])
A queue should not be the only copy of an event. If the process commits to SQLite and then crashes before putting the event into an in-memory queue, the event must still be discoverable. A background scan of published_at IS NULL closes that failure mode.
Recovering after a restart
A recovery procedure should not simply reconnect and continue from the latest live message.
A safer sequence is:
- Open the SQLite buffer.
- Read the committed checkpoint.
- Identify unresolved sequence gaps.
- Replay the missing interval from the upstream provider.
- Publish locally buffered events.
- Resume the live subscription from the checkpoint.
- Reconcile any overlap.
Conceptually:
async def recover_and_subscribe(buffer, provider, publisher):
checkpoint = buffer.checkpoint(
source="market-feed",
stream="trades",
epoch="current-session",
)
if checkpoint is not None:
resume_from = checkpoint["last_seq"] + 1
# Ask the provider to replay events after the checkpoint.
# Some providers require an opaque cursor instead.
replay = provider.replay_trades(after_sequence=resume_from)
async for raw_event in replay:
event = normalize(raw_event)
buffer.persist(event)
# Recover rows that were committed locally but not yet published.
publisher.publish_pending()
# Start the live feed from the same durable position.
async with provider.subscribe_trades(after_sequence=resume_from) as feed:
async for raw_event in feed:
event = normalize(raw_event)
buffer.persist(event)
The exact recovery path depends on provider capabilities.
Provider supports sequence-based replay
This is the strongest common case. The client can request all events after the checkpoint and process them through the same idempotent ingestion path.
It is often useful to request a small overlap, such as the last committed event itself. Duplicate events should then be discarded by the uniqueness constraint or ingestion identifier.
Provider supports an opaque cursor
The cursor must be stored exactly as issued. It should not be parsed, compared numerically, or reconstructed from a timestamp. It usually remains valid only for a particular stream and session.
Provider supports neither replay nor a cursor
The system cannot guarantee that the exact missing interval can be recovered.
Possible fallbacks include:
- A historical REST endpoint
- A snapshot followed by live updates
- Periodic full snapshots
- Another redundant market-data source
These alternatives have limitations. A REST response may not preserve the original sequence numbers or exact ordering. It may also update historical records rather than expose every intermediate trade.
When the source offers no replay mechanism, the correct statement is not “no data was lost.” The system can only reduce the loss window and detect some discontinuities.
Handling sequence resets and stream epochs
Sequence numbers are not always continuous for the lifetime of a logical stream. A provider may reset them after:
- A trading session changes
- A market reconnects
- The upstream sequence counter reaches its maximum
- A new partition or shard is activated
The stream_epoch field in the example separates different numbering domains.
A reset should not be interpreted as a huge gap:
Old epoch: 9,998,992
Old epoch: 9,998,993
New epoch: 1
New epoch: 2
The two epochs need separate checkpoints. Reset detection may be explicit, such as a subscription message containing sequence_reset, or implicit, such as observing a sequence that is lower than the checkpoint while the session identifier has changed.
Saving the last trade versus saving a trading signal
For a market-data recorder, the checkpoint naturally refers to the last durable input event.
For a signal-processing system, the situation is more complicated. The last output signal is not sufficient because:
- The signal may depend on a rolling window of historical inputs.
- An input may have been received but not yet processed.
- Restarting from the last output can reproduce or skip intermediate computations.
- A signal may have triggered an order or another external side effect.
A more reliable design separates the pipeline into stages:
Raw event
▼
Durable event buffer
▼
Deterministic feature or signal calculation
▼
Durable signal output
▼
External action through an idempotent outbox
The raw event and the checkpoint are persisted first. Signal calculations can then be replayed deterministically from a known input position.
If the signal produces an order, use a stable idempotency key derived from the signal version and strategy context. The outbox pattern prevents a crash between “order was accepted” and “order was recorded locally” from causing an accidental duplicate submission.
In other words, restarting a signal engine safely requires more than storing the latest signal timestamp. It requires a replayable input history and an explicit policy for side effects.
Graceful shutdown is only the first line of defense
Graceful shutdown reduces the number of events that need replay, but it cannot eliminate crash scenarios. A process can receive SIGKILL, lose power, or lose its container without executing shutdown hooks.
A proper shutdown sequence should:
- Stop accepting new WebSocket messages.
- Allow in-flight parsing and SQLite commits to finish.
- Stop the publisher from beginning new work.
- Give the publisher a bounded time to flush pending events.
- Close the WebSocket cleanly where possible.
- Leave unconfirmed events in SQLite for restart recovery.
An asyncio implementation might look like this:
import asyncio
import signal
async def main():
stop_event = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, stop_event.set)
buffer = DurableEventBuffer()
publisher = TickDBPublisher(buffer, create_tickdb_client())
async with connect_to_market_feed() as feed:
async for raw_message in feed:
if stop_event.is_set():
break
event = normalize(raw_message)
buffer.persist(event)
# Bounded drain. Pending rows remain in SQLite if this times out.
try:
await asyncio.wait_for(
publisher.publish_pending_async(),
timeout=10,
)
except asyncio.TimeoutError:
pass
The important detail is that the SQLite commit happens before the event is considered accepted. If shutdown interrupts the operation, recovery can inspect durable state.
However, graceful shutdown must not become the only recovery mechanism. A robust service should behave correctly after both orderly and abrupt termination.
Detecting gaps in real time
Even with a correct checkpoint, an application should expose gap information rather than silently proceeding.
Useful operational metrics include:
ingestion_events_received_total
ingestion_events_persisted_total
ingestion_events_published_total
ingestion_publish_retries_total
ingestion_sequence_gap_total
ingestion_oldest_pending_age_seconds
ingestion_checkpoint_lag_seconds
ingestion_replay_events_total
A sequence-gap alert might be triggered when:
incoming_sequence > checkpoint_sequence + 1
For a provider without sequence numbers, approximate monitoring can use:
- Expected heartbeat intervals
- Time between trades
- Comparison with a secondary source
- Differences between local and exchange session timestamps
These checks detect anomalies; they do not provide the same guarantee as a source sequence.
A practical recovery policy
A resilient service can use the following policy:
| Condition | Action |
|---|---|
| Restart with no local checkpoint | Start a new epoch and request a snapshot |
| Restart with a valid checkpoint | Resume after the checkpoint |
| Sequence gap detected | Replay the missing interval before continuing |
| Provider does not support replay | Fetch historical data if available and record an explicit recovery limitation |
| Duplicate event received | Ignore it using a stable event identifier |
| Crash after local commit | Republish pending SQLite rows |
| Crash after TickDB commit | Retry with the same ingestion identifier |
| Malformed event | Store it in a dead-letter path and do not advance the checkpoint |
The dead-letter path is important. A parser error should not silently block all progress, but it also must not allow the checkpoint to move past an event whose meaning is uncertain. The correct behavior depends on the protocol: some formats can safely skip malformed records, while others require a full resynchronization.
Testing the failure modes
A persistence design should be tested by injecting failures at every important boundary:
1. Kill the process immediately after receiving a message.
2. Kill it after SQLite commit but before publication.
3. Kill it after publication but before marking the row published.
4. Replay the same upstream event several times.
5. Deliver events out of order.
6. Reset the upstream sequence.
7. Corrupt one event.
8. Restart while the publisher is processing a batch.
9. Run the publisher and WebSocket writer in separate processes.
10. Fill the local disk and observe recovery behavior.
The expected result is not necessarily “exactly once.” In distributed systems, an honest objective is usually:
At-least-once processing with idempotent storage and deterministic reconciliation.
Exactly-once business effects may still be achievable when the external system supports idempotency keys, but the transport and database layers should not be described as exactly-once unless that property is actually verified.
Putting the design together
A practical implementation should follow seven rules:
- Persist before acknowledging progress. A received event is not processed until its durable state exists.
- Advance checkpoints transactionally. The event row and checkpoint must commit together.
- Advance only across contiguous sequences. A later event does not erase an earlier gap.
- Use stable identifiers. Retries must be harmless.
- Recover pending rows explicitly. Do not depend solely on an in-memory queue.
- Replay before live continuation when possible. Reconnecting directly to live data can miss the recovery interval.
- Treat local buffering and analytical storage as separate layers. SQLite closes the transactional crash window; TickDB provides durable, queryable market history.
For teams that need to retain normalized market events for historical analysis, strategy research, or replay, TickDB can serve as the long-term time-series destination while a local transactional journal handles the short-lived ingestion state. The exact benefit comes from combining those roles rather than expecting any single component to solve every failure case.
The central lesson is straightforward: reliable restart behavior is not a reconnect feature. It is a state-machine design in which every received event, checkpoint transition, replay request, and external publication has an explicit and durable meaning.
Publication Metadata
- Suggested slug:
graceful-shutdown-market-data-state-persistence - Meta description: Learn how to persist WebSocket market data, checkpoint stream positions, recover after restart, detect sequence gaps, and publish events idempotently to TickDB.
- Primary keyword:
market data state persistence - Secondary keywords:
WebSocket checkpointing,SQLite write-ahead log,market data replay,idempotent ingestion,TickDB - Suggested CTA: Explore using TickDB as the durable, queryable destination for normalized market events while a local transactional buffer handles recovery and exactly-once-style idempotency.
Editorial Evidence Notes
- The examples assume an upstream numeric sequence, an opaque resume cursor, or both. WebSocket providers differ materially; the article does not claim universal replay support.
- The TickDB DDL and ingestion call are representative and should be validated against the deployed TickDB version, SQL dialect, permissions, and client interface.
- SQLite
WALandsynchronous = FULLimprove local crash durability but do not protect data that was received and never committed. ReplacingMergeTreeprovides engine-level duplicate handling for identical sorting keys, but downstream consumers should account for merge semantics and use stable ingestion identifiers.- The recommended delivery guarantee is at-least-once processing with idempotent effects, not an unsupported claim of universal exactly-once delivery.