A typing indicator that can remain visible forever is modeled incorrectly. Treat typing=true as a renewable lease, not durable state: keep the stop event for fast cleanup, but make every client expire the indicator from the latest accepted start or refresh event. In a financial operations dashboard, where analysts may type notes while watching device status, this keeps an ephemeral collaboration hint from acquiring the authority of a ledger entry. The delivery system may duplicate, delay, reorder, or lose a transient event; the UI must still converge to idle.
TL;DR: attach a monotonically increasing generation to each actor's typing stream, refresh a short deadline while activity continues, ignore older generations, and clear locally when the deadline passes. Do not promise exactly-once delivery at fan-out. Make the visible result idempotent instead.
How do I debug a typing indicator that sticks forever?
Start and stop usually travel as separate messages. That separation creates an invalid state transition: the receiver can observe the first message without ever observing the second. A tab can close, a mobile network can change, a process can restart after accepting a start but before publishing a stop, or an unreliable data channel can discard one message. Even a reliable connection does not make a multi-hop path atomic when a gateway accepts one event and a downstream subscriber disconnects before the other arrives.
The trap is subtle because happy-path testing sends a balanced pair. Production fan-out does not preserve that comforting symmetry across reconnects and subscriber lifetimes.
Loss is normal.
WebRTC data channels also make the transport choice explicit. The ordered member defaults to true, while maxRetransmits or maxPacketLifeTime can bound retransmission; configuring either changes what the application may assume about delivery. Those controls are useful for short-lived signals, but they do not absolve the receiver from defining an expiry rule. A stale typing indicator is an application-state bug regardless of which hop lost the stop.
In the financial system, I would separate three classes of information. Ledger movements and reconciliation decisions require durable identifiers, audit trails, and duplicate suppression. Device status needs a declared freshness policy because a last-known value ages. Typing presence is weaker still: it is evidence of recent activity, never a fact that should survive without renewal. Giving all three the same retention and retry policy obscures their different correctness boundaries.
Define the state as a lease
A lease event needs little data: actor, conversation or work-item scope, generation, active flag, and the sender's event identifier for traceability. The receiver should base expiration on its own monotonic clock when it accepts an active event. A sender timestamp is valuable in logs, but using wall-clock time from another device to schedule expiry imports clock skew into the user interface.
Five seconds is a reasonable worked example, not a universal standard. Choose the interval from the sender's refresh cadence, normal scheduling jitter, and the longest false-positive window the product can tolerate. If active input refreshes every two seconds, a five-second lease permits one missed refresh and some delay; the exact figures must be validated under the deployment's latency and suspension behavior. Compliance retention limits may also require that audit records omit typed content and retain only the minimum event metadata needed for operational diagnosis.
The receiver transition is deliberately asymmetric. A newer active=true event installs or extends a deadline. A matching or newer active=false event clears immediately. Silence clears eventually.
Expiry wins.
package presence
import (
"sync"
"time"
)
type Event struct {
Actor string
Scope string
Generation uint64
Active bool
EventID string
}
type entry struct {
generation uint64
expiresAt time.Time
}
type Tracker struct {
mu sync.Mutex
ttl time.Duration
now func() time.Time
state map[string]entry
}
func NewTracker(ttl time.Duration, now func() time.Time) *Tracker {
return &Tracker{ttl: ttl, now: now, state: make(map[string]entry)}
}
func key(e Event) string { return e.Scope + "\x00" + e.Actor }
func (t *Tracker) Apply(e Event) {
t.mu.Lock()
defer t.mu.Unlock()
k := key(e)
current, found := t.state[k]
if found && e.Generation < current.generation {
return
}
if !e.Active {
delete(t.state, k)
return
}
t.state[k] = entry{
generation: e.Generation,
expiresAt: t.now().Add(t.ttl),
}
}
func (t *Tracker) Active(actor, scope string) bool {
t.mu.Lock()
defer t.mu.Unlock()
k := scope + "\x00" + actor
current, found := t.state[k]
if !found {
return false
}
if !t.now().Before(current.expiresAt) {
delete(t.state, k)
return false
}
return true
}
This example performs lazy expiry during reads, which is often enough for a UI-facing cache. A production client may also schedule one timer for the nearest deadline so the label disappears even when no render reads occur. Timer callbacks must recheck the stored generation and deadline; otherwise, a timer created for an older lease can clear a newer one.
The trade-off is visible latency against false presence. A very short lease can flicker when a tab is briefly suspended or a refresh is delayed; a long lease makes the original symptom less permanent but still conspicuous. This lease design is not suitable for facts that must remain true until explicitly reversed, such as a posted ledger entry or an approved reconciliation adjustment. Those records need durable commands, idempotency keys, persisted outcomes, and a replayable audit history. Presence expiry belongs only to hints whose truth decays with silence.
Short-lived state still deserves an audit trail, but not the same one as money movement. Log event ID, actor pseudonym, scope, generation, acceptance time, source connection, and transition outcome such as accepted, stale, duplicate, or expired. Do not log keystrokes. The point is to reconstruct delivery and state transitions without turning an activity hint into stored message content.
Delivery guarantees at fan-out
A broadcast path tempts teams to ask for exactly-once delivery. That phrase hides at least two boundaries: the broker may deduplicate publication while the browser applies the same event twice, or the browser may apply once and then lose its local state during reload. Exactly-once should be an outcome of idempotent state transitions and reconciliation, not a claim attached to a socket.
For typing presence, at-most-once delivery minimizes retries but makes expiry mandatory. At-least-once delivery can reduce missing refreshes, although duplicates then become ordinary input. Ordered delivery prevents an old start from overtaking a newer stop on one channel, yet reconnecting through a different channel can create a new ordering domain. A generation number closes that gap when its allocation rules are stable for the lifetime of the actor and scope.
| Fan-out property | Remaining failure | Receiver rule |
|---|---|---|
| At-most-once | Start or stop may be absent | Expire every active state |
| At-least-once | Starts and stops may repeat | Apply transitions idempotently |
| Ordered per connection | A reconnect can split order domains | Compare generations across connections |
| Bounded retransmission | Late data may be abandoned | Refresh before expiry and tolerate loss |
The generation must have an unambiguous owner. A per-tab counter is insufficient if two tabs represent the same actor and scope, because equal or overlapping counters cannot establish a total order. Either give each producer a distinct session identifier and track sessions separately, or allocate the generation in a single authoritative stream. The first choice fits ephemeral presence: the display can show the actor while any unexpired session remains active, and each tab can clean up only its own lease.
Never let the typing path mutate the canonical device record. In an operations dashboard, live device status may arrive beside the presence stream and share a visual row, but it has a different source, freshness window, and reconciliation procedure. Joining them for rendering is fine. Sharing a state machine is not.
Debug the missing transition, then prove expiry
Begin at the receiver, because the symptom exists there. Capture one correlation chain from input activity through publisher acceptance, fan-out, client receipt, state application, and timer expiry. The useful question is not merely "was stop sent?" It is "what was the last accepted generation for this actor, scope, and session, and why is it still visible?"
Consider a deterministic trace rather than a vague report that the label "sometimes hangs." At 0 milliseconds, session A publishes generation 41 as active and the client sets a deadline at 5,000 milliseconds. At 2,000 milliseconds, generation 42 refreshes the lease and moves that deadline to 7,000. The stop for generation 43 is then dropped during a reconnect. If the old timer created for generation 41 fires at 5,000 and clears the entry without checking its current generation and deadline, the UI flickers off too early; if no timer survives the reconnect, it sticks forever. The correct callback reads current state, observes generation 42 with a 7,000-millisecond deadline, and leaves it alone until that deadline. At 7,000, it expires the entry even though stop 43 never arrived. This trace distinguishes two independent bugs: stale timers clearing renewed state and missing timers preserving abandoned state. It also gives logs a concrete invariant: after accepting an active event, the same session and scope must produce a later stop, replacement, or expiry outcome.
Use structured counters for starts, refreshes, stops, stale drops, duplicate drops, expirations, reconnects, and active leases. Compare accepted starts with terminal outcomes over a bounded observation window. They need not balance instantaneously, but every accepted lease must eventually terminate through stop, replacement, session removal, or expiry. Alert on lease age above the configured maximum rather than on raw stop-event counts; a stop can legitimately be absent after an abrupt disconnect.
Testing should attack the transitions, not the animation. With a fake clock, verify duplicate start, duplicate stop, stop-before-start, delayed old start after a newer stop, repeated refresh, timer firing after renewal, reconnect with a new session, and process restart with an empty ephemeral cache. Then run an integration test that drops every stop event. The indicator must still disappear within the lease bound.
A second integration test should duplicate every message and reorder adjacent messages. No panic, negative counter, or permanent indicator should result. For a dashboard carrying device status, inject that traffic concurrently and verify that presence loss never suppresses, delays, or changes the device state pipeline. This isolation test matters because shared queues and shared backpressure policies can couple two otherwise separate models.
Roll out the repair without hiding regressions
Deploy in two stages. First, add generations, session identity, expiry metrics, and client-side leases while retaining stop events. Observe the distribution of lease ages and record which terminal path clears each entry; this establishes whether the chosen deadline causes visible flicker or leaves stale state too long. Second, enable timer-driven rendering for a small cohort, then widen only after reconnect and expiry outcomes remain within the declared limits.
Keep the stop event. Expiry is the correctness backstop, while stop provides responsive cleanup under normal delivery. During migration, old events without a generation can live in a separate compatibility lane with a shorter fixed lease; they must never overwrite versioned state. Remove that lane after the maximum supported client lifetime, rather than guessing that all old clients have disappeared.
The durable lesson is compact: a typing signal describes recent evidence, so absence of renewal must mean absence of display. Once the client owns that invariant, a missing stop becomes observable packet loss rather than permanent false state, and the delivery guarantees of the fan-out layer become a design input instead of an unsupported promise.
Top comments (0)