Mirexa

Wiki Guides

Subscribing to live data

How to receive a Mirexa stream's history and then its new data as it is written — the backfill-to-live switch and its duplicate rule, drop detection, slow-consumer eviction, bounded-ack delivery, and resuming after a disconnect.

A subscription pushes a stream's data to you as it is written, instead of you polling for it. With backfill, it first sends the stream's stored history from a point you choose, then switches to live data, so a consumer can start from a known position and keep up without a gap. This page covers the guarantees at that switch, how to tell when data was dropped, and how to survive a disconnect.

Subscribing

go
sub, err := c.SubscribeStream(ctx, client.SubscribeRequest{
	StreamID:  stream,
	Backfill:  true,            // send stored history first
	StartTime: from.UnixNano(), // backfill from here; 0 = the earliest stored record
	// Ticks: true              // trades instead of candles
})
if err != nil {
	return err
}
defer sub.Close()

for sub.Next(ctx) {
	ev := sub.Event()
	if ev.Live {
		// the backfill is done; everything from here on is real time
	}
	if ev.Dropped > 0 {
		// batches MissingFirst..MissingLast are gone, not delayed
	}
	use(ev.Candles) // or ev.Ticks
}
if err := sub.Err(); err != nil {
	return err
}

From the command line:

bash
./bin/cli subscribe -stream binance:BTCUSDT:1m -backfill

subscribe prints records as CSV with Unix-nanosecond timestamps, and reports the switch to live and any drops on standard error. Flags: -backfill, -from (Unix ns; requires -backfill), -ticks, -count (stop after N records) and -resume (reconnect and continue after a dropped connection).[1]

Subscribing needs the read permission for what you subscribe to (READ_CANDLES or READ_TICKS).

What arrives

Each event is one batch, as it was written:

Event field Meaning
Candles / Ticks Exactly one is populated. Both may be empty on an event that only signals a state change.
Backfill This batch is stored history.
Live The first live batch after the backfill. Never set without backfill.
Sequence Live batches are numbered from 1; backfill batches carry 0.
Dropped, MissingFirst, MissingLast Batches the node discarded because you were not keeping up.
Stale, LevelAt Cluster only: the batch came from a copy, which trails its primary by about one replication poll.

Live delivery is post-commit and in log order: a batch reaches subscribers once it is durable in the node's log, and a stream's batches arrive in the order they were logged, corrections included.[2] Only closed candles are ever sent; asking for in-progress candles (Partials) is refused with Unsupported.

What a subscriber sees, by kind of write:

  • New bars, restated bars that changed, and bars the node derives — yes.
  • A restated bar identical to what was stored — no; nothing was written.
  • Bars installed through the history route bypass the log, and the source suggests they are not pushed to live subscribers (inferred from the source; not covered by a test). A query or a backfilling subscription sees them.

The backfill-to-live switch

At the switch there is no gap, but there can be duplicates. The backfill window and the live queue overlap on purpose, so a record written while the backfill was being read can arrive on both sides of the switch. Candles are keyed by (stream, timestamp); if duplicates matter to you, keep the last value per key.[3] (For ticks, which have no key, a duplicate at the switch is indistinguishable from a second trade at the same timestamp.)

Drops and slow consumers

The node keeps a bounded queue per subscription (network.subscription.queue_depth, 64 batches by default). By default delivery is fire-and-forget: when your queue is full, the node drops the batch, and the next one you receive says how many were dropped and which sequence numbers they had.[4]

  • A dropped batch is gone, not delayed. Recover its range with a query, or re-subscribe with backfill from before it.
  • Do not detect drops from Sequence yourself. There are two sequence spaces (live from 1, backfill at 0); the SDK already accounts for both and reports Dropped.
  • After network.subscription.drop_limit consecutive drops (default 10,000, about a second of a consumer making no progress) the node evicts the subscription with SlowConsumer; Next returns false and Err() is ErrSlowConsumer. The connection stays open. One successful delivery resets the count.[5]

Bounded-ack delivery

Setting SubscribeRequest.AckWindow to a non-zero value selects bounded-ack delivery: the node sends at most that many live batches beyond the last one you acknowledged, and never drops one — a subscriber that falls too far behind is evicted instead. The SDK acknowledges for you: calling Next is what says you have processed the previous batch.[6]

Rules for the consumer

  • One subscription per Client; request/response calls on the same client run alongside it freely. A node accepts up to network.subscription.max_per_connection (256) on one connection, which the multi-stream subscriber inside the repository uses; the public Go package exposes one per client.
  • One goroutine drives a Subscription.
  • Keep reading. The client's push buffer is bounded; a consumer that stops reading eventually stalls every request on that client, and the node evicts it long before.
  • Quiet is normal. No request timeout applies to Next; bound it with the context.
  • Copy before keeping. An event's slices alias the frame's buffer; copy what you keep past the next Next.
  • sub.Close() stops iterating but does not tell the node; call sub.Unsubscribe(ctx) first if it should stop sending.

Resuming after a disconnect

client.NewResumingSubscriber survives a lost connection. When the connection fails it redials, repeats the handshake, and re-subscribes with backfill from one nanosecond after the last record it delivered, so you see one continuous stream:[7]

go
// opts carries a TokenSource, as in Writing data; each redial re-reads the token.
s, err := client.NewResumingSubscriber(addr, opts,
	client.SubscribeRequest{StreamID: stream, Backfill: true},
	client.ResumeOptions{}) // MaxAttempts 5, Backoff 200ms
if err != nil {
	return err
}
defer s.Close()
for {
	ev, err := s.Next(ctx)
	if err != nil {
		return err // ctx ended, or the reconnect budget was spent
	}
	use(ev)
}
  • The original request's Backfill applies to the first subscribe only; every reconnect backfills, because that is what fills the hole the disconnect left.
  • s.Reconnects() and s.Redirects() count what happened.
  • In a cluster, ResumeOptions.FollowRedirects lets it follow a stream whose partition moved; by default a candle subscription may also be offloaded to an in-sync copy when its primary is saturated (NoOffload keeps it on the primary).

Resuming from one nanosecond past the last record is exact for candles, which have one bar per timestamp. For ticks, a trade sharing its timestamp with the last one delivered but arriving in a later batch would be skipped by the resume (inferred from the resume rule; not covered by a test). If that matters, re-subscribe from the last timestamp itself and drop what you already have.

References

Source

Tests

Further reading


  1. runSubscribe, validateBackfillFlags in /cmd/cli/main.go. ↩︎

  2. The feed installed by dispatcher.SetOnIngest in /internal/network/server.go. ↩︎

  3. TestServer_BackfillLeavesNoGapAtTheLiveBoundary, TestCLI_BackfillToLivePivotReachesTheUser. ↩︎

  4. TestSubscriptionRegistry_DroppedBatchLeavesSequenceGap, TestSubscription_BackfillBatchesAreNotDrops. ↩︎

  5. SubscriptionConfig.DropLimit in /internal/config/config.go; TestServer_SlowSubscriberIsEvictedWithSlowConsumerError. ↩︎

  6. TestServer_AnAckedSubscriberIsSentNoMoreThanItsWindow, TestServer_AnAckedSubscriberIsEvictedNotDroppedFrom. ↩︎

  7. resumeFrom = newest + 1 in /internal/wireclient/resume.go; TestResumingSubscriber_SurvivesADroppedConnection. ↩︎