Push as a Hint, Not a Message: Server-Triggered Sync for Always-On Agents
Executive Summary
An always-on agent that holds a WebSocket to a coordination server and polls a catalog every few minutes has a latency problem: a server-side change can wait up to one poll interval before the agent notices. The obvious fix is a server push that tells the agent something changed and it should sync now. The design question is what that message is allowed to mean.
The literature's answer is consistent: a push is an invalidation hint, and the state the agent acts on is whatever the agent pulls itself, through the same path the periodic poll uses. Mobile push providers document that delivery is not guaranteed and that a content-free "ping" is the way to ask an app to sync. Dropbox webhooks say only which accounts changed and make you fetch the changes with a cursor. Stripe's thin events carry a pointer and tell you to fetch the latest object. Kubernetes controllers are level-triggered, so a missed event costs latency, not correctness.
This article examines one concrete design (described in section 1): a hint-only push, validated and deduplicated by id, feeding a coalescing queue that runs a fixed local sync command, with a sync on every WebSocket open and the periodic poll kept as the backstop.
Main conclusions:
- The pull is the truth. If the push carries no state, loss, duplication, reordering and forgery degrade into an extra sync or a late sync.
- Resync on every connect. Push channels are generally at-most-once across a disconnect. Gap detection suits expensive pulls or streams you cannot recompute; when a full pull is cheap and idempotent, unconditional resync is simpler and safer.
- Coalescing must not drop the last signal. A request that arrives mid-run may postdate the run's reads, so merging it into the running work (as single-flight does) loses the update. The Kubernetes workqueue's dirty and processing sets model the right behavior. The same holds across processes: a sync that exits because another sync holds the lock has done nothing for its request, so the queue keeps the request and retries.
- Dedup is an optimization when the action is idempotent, but cheap enough to keep.
- Safety comes from what the push cannot express: fixed command and argv, no shell, one strictly validated field, a timeout that frees the slot only once the process is confirmed gone, no raw logging of untrusted text, an authenticated channel.
- Keep the poll and add jitter at fleet scale. The poll bounds staleness only while polls run on schedule and succeed.
The article separates what a cited source says from our own recommendation. Items we could not verify are listed in the final section.
1. The illustration
This is a constructed example for discussion, not a report of any particular system.
An always-on agent holds a long-lived WebSocket to a coordination server and polls a market (a catalog of things to install or update) every five minutes. Without pushes, the delay between a change and the agent acting is about the poll interval plus the sync duration, and only if the next poll runs on schedule and its sync completes; a failed or busy poll, waiting behind a sync already in flight, and any cooldown add to it (section 7.2). Shortening the interval raises market load linearly with fleet size, and most polls find nothing.
The server gains a frame meaning roughly something changed, sync now. The agent's rules:
- It runs a fixed local sync command with a fixed argument vector, no shell and a 60-second timeout; nothing from the frame reaches the command, its environment or its files.
- It accepts a push only if the frame names this agent and carries a request id of restricted charset and length; other fields are ignored.
- It drops duplicate ids (last 256, or 10 minutes).
- Accepted requests enter a coalescing queue: when idle, a request runs at once (leading edge); during a run, a request sets one follow-up slot that runs when the run ends; within 2 seconds after a run, a request sets the same slot and the follow-up runs at the end of those 2 seconds; at most one run is queued.
- Pushes sent while the agent was offline are not redelivered, so every WebSocket open, including the first after a restart, enqueues one sync through the same queue.
- The five-minute poll continues unchanged. In this example it does not go through the queue: it starts the same sync command on its own schedule.
- The sync command takes a lock of its own. If another sync already holds it (one started by the poll, or by another process), the command exits at once with a distinct busy code. How the queue should treat that exit is not obvious; section 5.3 shows that counting it as success can lose an update, and section 8.1 gives the rule.
As a state machine, three states and one boolean suffice:
| State | Meaning | New accepted request | Run ends |
|---|---|---|---|
| idle | nothing running, cooldown over | start a run; go to running | n/a |
| running | command in flight | set the pending flag | go to cooling; if flagged, schedule one follow-up |
| cooling | within 2 s of a run's end | set the pending flag; make sure a timer fires at the end of the window | n/a |
The flag is a boolean, not a counter: ten requests during a run and one request produce the same single follow-up. That is the whole coalescing rule. Run ends here means the child process is confirmed gone, not merely that a timeout fired (section 6.3). One detail the description leaves open, whether a follow-up queued during a run starts immediately or after the cooldown, matters for the maximum run rate and is taken up in section 5.5.
2. Why a push should be an invalidation hint
2.1 What the sources say
Event notification. Martin Fowler separates "Event Notification" from "Event-Carried State Transfer." In the first, "An event need not carry much data on it, often just some id information and a link back to the sender," and the recipient "then issues a request back to the sender to decide what to do next." It buys low coupling and simplicity, at the price of flows that are hard to see in program text. In the second, events carry the data, which buys resilience but "does involve more complexity on the receiver, since it has to sort out maintaining all the state." The illustration is the first pattern.
Mobile push. Firebase Cloud Messaging defines a collapsible message as one that "may be replaced by a new message if it has yet to be delivered to the device," and describes the sync use case: "messages used to tell a mobile app to sync data from the server," and a content-free "ping" to an app. For non-collapsible messages on Android there is a cap of 100 stored messages; when it is hit "all stored messages are discarded," the device later receives a special message, and the app can handle the situation "by typically requesting a full sync from the app server." A returned message ID "doesn't mean that the message was already delivered to the device," only that "it was accepted for delivery"; RFC 8030 (Web Push) says likewise of a 201 response. Apple's documentation says the system "treats background notifications as low priority: you can use them to refresh your app's content, but the system doesn't guarantee their delivery," may throttle them, advises not to "send more than two or three per hour," and, when several arrive, discards the older one and holds only the newest.
Dropbox. The webhook payload "does not include the actual file changes" and "only informs your app of which users have changes"; the app then calls list_folder/continue with its stored cursor. Long-poll will "block until a change is detected (or its timeout occurs)" and likewise returns no changes.
Stripe. Events may arrive more than once and out of order; "You can also use the API to retrieve any missing objects." Thin events come with fetchRelatedObject() "to retrieve the latest version of the object associated with the event."
Kubernetes. Controllers are level-triggered rather than edge-triggered. James Bowes's explanation (which opens with a quotation from Joe Beda) notes that "If a system does not sample the signal frequently enough, it may miss a trigger," and that an edge-triggered view can end in "a state that the original signal was never in." He writes: "In a level triggered system, we always compare the complete desired and actual states." Such a system reaches the correct end state after a disruption, with a delay. Bowes says problems of edge-triggered systems are often mitigated through "a periodic reconciliation with the full state," and also through "an explicit ordering and versioning of events."
2.2 What this means for an agent
If the push carries state, each failure mode of the push path (loss, duplication, reordering, delay, forgery) becomes a state-corruption risk, and you need sequence numbers, replay and idempotency tables. If it carries no state, those failures reduce to extra or late syncs. In the illustration the one useful field, the request id, serves only deduplication and log correlation; the agent learns that it should ask, not what to fetch. That also limits the security exposure (section 6): a forged push can influence whether the agent syncs soon, not what the agent runs. Thin payloads do have the cost Fowler names, that flows are hard to trace, so record the trigger (push, open, poll) and request id with each run.
3. Delivery semantics and what a disconnect loses
3.1 What a socket gives you
Frames on an open WebSocket arrive in order for as long as the connection lives. That is a property of the connection, not of the system. When the connection drops, any frame the server wrote but the client did not process is gone, and the server usually does not know which. Nothing replays them unless the protocol builds that in, which takes three things: a message identity, a receiver acknowledgement, and a sender retry or replay policy.
| System | What the source says |
|---|---|
| Web Push (RFC 8030) | Stored until a TTL; the service "SHOULD continue to retry delivery of the message until its advertised expiration," but "MAY cease to retry delivery of the message prior to its advertised expiration" (for example for an unresponsive user agent), may expire a stored message before its TTL, and "is not obligated to store messages indefinitely"; a zero-TTL message "expires and is never delivered" if the user agent is unavailable |
| FCM | Held for offline devices until delivered or expired (by default up to four weeks); stored non-collapsible messages capped, then discarded with a signal to resync |
| Stripe webhooks | Retried "for up to three days with an exponential back off in live mode"; duplicates and reordering possible |
| GitHub webhooks | "GitHub does not automatically redeliver failed deliveries"; redeliver missed ones yourself after an outage |
| Slack Socket Mode | Each event must be acknowledged "so that Slack knows whether to retry"; connections are refreshed regularly, and the docs suggest several connections "to maintain uptime during a connection restart." The warning that "you may lose events until you establish a connection" applies to an app that is already receiving events when Socket Mode is toggled on, until its first connection is up |
| Discord gateway | On resume the gateway "will send the missed events in order, finishing with a Resumed event"; a failed resume needs a fresh identify |
Nobody offers exactly-once delivery to the consumer. The offers are at-most-once, at-least-once or best effort, and the consumer must tolerate the failure mode. Even systems with retries and replay document an outer limit (three days, four weeks, a short session window, an overflow cap), and RFC 8030 lets a push service give up before its own advertised limit; beyond that a full resync is the only cure. The illustration states its semantics plainly: pushes sent while the agent was offline are not redelivered, which is at-most-once across a disconnect.
3.2 Two ways to close the gap
Gap detection gives each event a position (sequence number, cursor, resource version). The client remembers the last position it processed; on reconnect it asks for events after that position, and if the server no longer has them the client does a full resync. Three cited systems work this way:
- Discord's client caches the latest non-null sequence number
sand sends it with the session id when resuming; if resuming is impossible the server sends Invalid Session and the client re-identifies. - Kubernetes lets a client restart a watch "from the last returned
resourceVersion." History is short ("Clusters using etcd 3 preserve changes in the last 5 minutes by default"), and clients "must handle the case by recognizing the status code410 Gone, clearing their local cache," then listing again and watching from the returned version. Bookmarks exist "To mitigate the impact of short history window," but clients cannot assume "the API server will send anyBOOKMARKevent even when requested." - Dropbox describes folder cursors as "pointers to the folder at a particular time"; continuing with an expired one returns "a 409 reset error" and the client must list again.
In each case gap detection is an optimization on top of an unconditional fallback (relist, re-identify, reset), because the history window is finite. Unconditional resync skips the optimization: on every connect, pull everything and reconcile.
3.3 When each is right
This is our analysis, not a sourced claim. Gap detection pays off when the pull is expensive, when the stream carries information that cannot be recomputed from current state (audit trails, counters, order-sensitive deltas), or when each event must be acted on exactly once and the action is not idempotent. Unconditional resync is better when the pull is cheap, the action reconciles desired against actual state, and the full-pull path already exists because the poll uses it.
The illustration fits the second description. Sequence numbers would need per-agent event history on the server, expiry rules, and a replay protocol with its own failure paths, all ending at the fallback the design already has: do the full sync. The open-triggered sync is the level-triggered reconciliation Bowes describes, and because it goes through the same queue, a flapping connection that opens repeatedly collapses into at most one run plus one follow-up. The first open after a restart is included because the agent then has no memory of what it missed and the next poll may be minutes away.
3.4 What a reconnect does not cover
A reconnect sync covers pushes missed while the socket was down, not a push sent while the socket looked up but was dead (a half-open connection). Application heartbeats bound that state (Discord requires a heartbeat ACK and treats a missing one as a sign of a failed or zombied connection), and the poll is the final cover. RFC 6455 provides the transport tool: "A Ping frame may serve either as a keepalive or as a means to verify that the remote endpoint is still responsive."
4. Deduplication
4.1 Why duplicates occur
With at-most-once push one might expect none. They still happen: the server's fan-out retries a send it believes failed; a bug or multi-process server sends the same notification twice; two connections for the same agent briefly overlap during a reconnect (Slack's Socket Mode allows up to 10 open connections at the same time, and when several are active "each payload may be sent to any of the connections"); or a later server version moves to at-least-once underneath the agent.
Stripe's documentation is direct: "You can guard against duplicated event receipts by logging the event IDs you've processed, and then not processing already-logged events." Its section on event ordering adds that snapshot events record created in seconds, so "distinct events can share a timestamp," and tells integrators not to use created to decide event order or whether an event was already processed, but to track event IDs instead. GitHub points to the X-GitHub-Delivery header for uniqueness and notes that on a manual redelivery it "will be the same as in the original delivery," so a redelivery you want looks like a duplicate. An id window can suppress a replay you actually want; this matters if the server ever adds redelivery.
4.2 Idempotency keys, and when they are unnecessary
Stripe's API reference describes the client-side counterpart: for API v1 it saves the status code and body of the first request made with a key and returns them on retries; keys are up to 255 characters and may be pruned once they are at least 24 hours old. It notes that GET and DELETE requests need no key because they "are idempotent by definition."
That sentence is the point. Idempotency keys protect actions that are harmful when repeated, such as charging a card. If the action is already idempotent, a key adds no safety, only saved work. The illustrated sync is a reconcile: run twice with no change in between, the second run does nothing. Dedup is therefore not a correctness requirement. It is justified because it removes redundant runs, stops duplicate frames from consuming the single follow-up slot, and gives a natural place to enforce that ids are well formed.
4.3 Bounds and a distinction
The two bounds do different jobs. The count bound (256) caps memory however many distinct ids a bug or attacker sends. The time bound (10 minutes) says how long a duplicate is plausible; retry and overlap duplicates arrive within seconds. An id that falls out of the window and reappears costs one redundant sync, so the bounds can be small. Our recommendations: use a monotonic clock for the time bound, and check the window before the queue so a duplicate never sets the pending flag.
Dedup by message id (have I seen this exact message?) differs from dedup by work (is this work already scheduled?). Id dedup guards against one message arriving twice; coalescing guards against many different messages asking for the same work. The illustration has both, and they are complementary.
5. Coalescing: single-flight with a dirty flag
5.1 The vocabulary
Debounce. Lodash documents _.debounce as delaying invocation "until after wait milliseconds have elapsed since the last time the debounced function was invoked." leading defaults to false, trailing to true, and maxWait bounds the delay. With both edges on, the trailing call happens "only if the debounced function is invoked more than once during the wait timeout." Debounce waits for quiet, so under a steady trickle without maxWait it can starve.
Throttle. _.throttle "only invokes func at most once per every wait milliseconds," with both edges defaulting to true. The docs' example uses { 'trailing': false } to invoke renewToken on click "but not more than once every 5 minutes": calls during the wait are simply dropped. Fine for a token renewal; a bug for an invalidation hint, because the dropped call may be the one signaling the last change. David Corbacho's article (linked from Lodash) states the cadence difference: "throttle guarantees the execution of the function regularly, at least every X milliseconds."
Single-flight. Go's singleflight executes a function while "making sure that only one execution is in-flight for a given key at a time," and when a duplicate comes in, "the duplicate caller waits for the original to complete and receives the same results." That is right for a cache fill, where every caller wants the value as of now. For invalidation it is wrong: a caller arriving mid-run is saying that something changed after the run may already have read the state, and sharing the in-flight result hands it a snapshot that may predate its change.
5.2 The Kubernetes workqueue
The client-go workqueue is the closest published analogue (we read the current source). It has three structures: queue (order of work), dirty (every item that needs processing; the deduplication set) and processing (items held by a worker, which "may be simultaneously in the dirty set"). The stated invariant: "Every element of queue should be in the dirty set and not in the processing set."
Add: if the item is already dirty, nothing new is enqueued. Otherwise it goes intodirty; if it is currently being processed,Addreturns without queueing it; if not, it is queued and a waiter signaled.Get: blocks until an item is available, moves it fromdirtytoprocessing, and returns it; "You must call Done with item when you have finished processing it."Done: removes the item fromprocessing; if it became dirty meanwhile, it is queued again.
So the same item is never processed by two workers at once, and any number of re-adds during processing collapse into one reprocessing after Done. The identity matters: the queue holds keys that identify objects, not events. A thousand events for one object become one key, and the reconciler reads current state when it runs. This is push as a hint in its purest form, and why controllers survive dropped and duplicated watch events.
The mapping is direct: the agent has one constant key, sync; Add while idle is the leading-edge run; Add while processing is the pending flag; Done with dirty set is the single follow-up; one worker per key is single-flight. Two differences. The plain workqueue re-queues in Done at once, with no time dimension (delay and rate limiting live elsewhere in the package; we did not verify those variants), so the 2-second cooldown is an extra layer. And with one key and one worker, the limit of one queued run falls out of the data structure. The workqueue's config also has a Clock field, commented as the ability to inject a real or fake clock for testing, and the constructor sets it to clock.RealClock{} when none is given; that matters for testing (section 9).
5.3 The lost-update window
- t0: the agent starts a sync run.
- t1: the run reads the market's state (version 41).
- t2: the market moves to version 42 and the server pushes.
- t3: the push arrives; a run is in progress.
- t4: the run finishes, having installed version 41.
If the agent handles the t3 request by ignoring it because a run is in progress, or by sharing the in-flight result, it stays at version 41 until the next poll, up to five minutes later. Every component behaved by its own rules and the update was still lost: the signal and the work overlapped so as to make the signal invisible.
The dirty flag closes it. At t3 the agent records that something changed after this run may have read its inputs; at t4 it starts one more run, guaranteed to start after the push arrived. One follow-up suffices, since all requests arriving during the run share one obligation. It cannot be skipped because the run just started, since the agent cannot know whether the run has already read its inputs. And a request that arrived before the run read its inputs earns a redundant follow-up, the price of not knowing; with an idempotent reconcile the second run finds nothing and exits quickly. The invariant to test: for every accepted request there is a run that starts at or after the request's arrival and actually performs a reconciliation.
The same window across processes. In the illustration the poll starts the sync command outside the queue, and the command exits busy when another sync holds its lock. Replay the timeline with that: at t0 a poll-started sync (another process) begins; at t1 it reads version 41; at t3 the push for 42 arrives, the queue is idle, so it starts the command at once; the command finds the lock held and exits busy; at t4 the poll's sync finishes at 41. If the queue counts busy as success, the obligation from t3 is gone and the agent stays at 41 until the next poll. A busy exit means another sync is running, not that the running sync will see the change.
Our recommendation, in order of preference:
- Route every trigger through one in-process scheduler. If the poll, the push and the open all enqueue into the same queue, there is no busy case between them: the queue's pending flag covers all three. The command's own lock then only guards against invocations from outside the agent.
- If a sync can still be started outside the queue, the queue keeps the obligation. A busy exit is never done: keep the pending flag and retry after the cooldown (backing off on repeated busy exits, as for failures in 8.3) until a run of the queue's own completes a reconciliation. The poll's sync will release the lock eventually, and the retry after it reads the current state.
A tempting shortcut is to let the busy process hand its request to the lock holder through a cross-process rerun marker that the holder checks before it exits, and then retire the request. Even with the marker set before the lock attempt and checked after release, so that no marker slips past the lock, the obligation now sits in a process the queue cannot watch. If the holder dies before its check, the marker has no consumer; if it clears the marker for a rerun and then fails or is killed before reconciling, the request is gone. Making that safe needs an owner that recovers stale markers and retries failed passes, which is the queue's job already. A marker can at most shorten the wait; it cannot let the queue retire the request.
Dropbox documents a server-side cousin: when a user makes changes in rapid succession, an app "is likely to receive multiple notifications for the same user at roughly the same time," and when work is not idempotent the app must make sure it "never processes the same user on multiple threads/processes at the same time." Dropbox adds: "The simplest solution is to use leases." A lease is the cross-process form of single-flight, and like single-flight it keeps two processes from working at once without by itself carrying a request that arrives while the lease is held; the requester still has to keep and retry its own obligation.
5.4 Leading edge, trailing edge, cooldown
In lodash terms the illustration is a throttle with leading: true and trailing: true, with two differences: the wait is measured from the end of the run, not its start (lodash's documentation counts from invocation and says nothing about asynchronous completion; for a sync lasting tens of seconds the 2 seconds should be breathing space after the work), and the trailing run is driven by a dirty flag that explicitly covers requests during the run.
The leading edge gives the common case, one push after quiet, minimal latency. The trailing edge ensures the tail of a burst produces a run that starts after it; without it the last signal is lost, as in the trailing: false case. The cooldown limits how fast runs can follow each other and lets near-simultaneous pushes collapse into one follow-up.
5.5 Does the follow-up wait for the cooldown?
The description says a follow-up requested during a run "runs when the run ends," and one requested within 2 seconds after a run "runs at the end of those 2 seconds." The first clause has two readings: the follow-up starts the moment the run ends, or at the end of the cooldown that begins then.
Under the immediate reading, a steady stream of pushes, each landing during the previous run, can produce back-to-back runs bounded only by run duration. Under the cooled reading the rate is at most one run per (duration + 2 s) whatever the push rate. Our recommendation, a design preference and not a sourced claim, is the cooled reading with one uniform rule: no run starts within the cooldown after the previous run's end, except the leading-edge run after idleness. The cost is up to 2 seconds of follow-up latency, small beside the five-minute poll. Whichever is chosen should be written down and tested, since the two are indistinguishable in a quiet test.
Even then the guard is local. For N agents a flooding sender can still cause up to N/2 syncs per second at the market. The local queue protects the machine, not a shared backend; that is a server-side job (section 7.4).
6. Safety: a push must not become remote code execution
6.1 Two threats
Forged or tampered pushes are a channel-authentication problem. A legitimate but compromised, buggy or confused server is a different one: the frame arrives on an authenticated channel carrying content that should not be trusted. If the channel is the only control, any server flaw becomes a flaw in every agent, so the second threat must be handled even when the first control is perfect.
6.2 Authenticating the channel
For HTTP webhooks every cited provider stresses sender authentication, since anyone can POST to a public URL. Stripe signs events with an HMAC over a timestamp and the raw body, rejects deliveries outside a timestamp tolerance (five minutes by default in its libraries) to prevent replay, and warns: "Without verification, an attacker could send fake webhook events to your endpoint to trigger actions like fulfilling orders, granting account access, or modifying records." GitHub tells integrators to validate deliveries with a high-entropy secret.
An agent-initiated WebSocket has no inbound endpoint to forge requests against. Slack's Socket Mode documentation says inbound events need no validation because they arrive "over a pre-authenticated WebSocket." The controls then sit on the connection: TLS with real certificate validation, and mutual authentication of agent and server. We found no normative source prescribing more for server-initiated frames and claim none. Two observations of our own: per-frame signatures are optional on an authenticated TLS channel but cheap if frames ever carry more than a hint; and the check that the frame names this agent is a routing check, not a security control. It guards against a server bug that fans one agent's notification out to all connections.
6.3 Narrowing the interface
Fixed command, fixed argv, no shell. Node's documentation draws the line. Of exec it says: "Spawns a shell then executes the command within that shell," with the warning "Never pass unsanitized user input to this function." execFile "does not spawn a shell by default"; the executable is "spawned directly as a new process." For execFile and spawn the warning is conditional: "If the shell option is enabled, do not pass unsanitized user input to this function." CWE-78 lists as mitigations replacing functions that invoke a command shell with a single string by ones that take individual arguments, using "structured mechanisms that automatically enforce the separation between data and code," and an "accept known good" input validation strategy (which it says may provide some defense-in-depth), and flags argument injection (CWE-88): even without a shell, untrusted text used as an argument can be read as an option. The illustration chooses the safest option: nothing from the frame goes into the command at all, so both classes are impossible by construction. The request id is only a key in an in-memory set and in log lines.
Strict validation of the one field used. Charset and length limits bound dedup memory and remove characters that matter in log formats. RFC 8030 offers a protocol-level precedent: its Topic header is restricted "to no more than 32 characters from the URL and a filename-safe Base 64 alphabet," with a 400 otherwise.
Ignore unknown fields. This is our recommendation: a field the design does not use cannot be abused, and tolerating extra fields lets the server evolve without breaking agents. Stripe offers an analogous precedent for one header rather than for payloads: its Stripe-Signature header carries comma-separated entries, and "Your integration must accept unknown entries and must not depend on a fixed entry count or order."
Timeouts that actually end the run. Node's timeout option only sends a signal: "the parent process will send the signal identified by the killSignal property (the default is 'SIGTERM') if the child process runs longer than timeout milliseconds." The same documentation warns that "the signal delivered to the child process may not actually terminate the process," and that "On Linux, child processes of child processes will not be terminated when attempting to kill their parent." maxBuffer terminates a child whose output exceeds the limit (default 1024 * 1024 bytes for exec and execFile). The contract we recommend on top of that (ours, not a source's):
- Spawn the command with
detached: true. On non-Windows platforms the child "will be made the leader of a new process group and session," so the agent can signal the whole group by passing the negative pid tokill(POSIX process-group semantics, not something the Node page states). - On timeout, send
SIGTERMto the group, wait a grace period, then sendSIGKILLto the group. - Release the running slot only after the child's exit is confirmed (the
exitorcloseevent) and, where the command starts helpers, the group is gone. - If termination cannot be confirmed, keep the slot held, start no new runs, and raise an alert. A visible stall is better than a new sync overlapping a half-dead old one.
- A runner error after a successful spawn (a failed signal call, a lost handle) says nothing about whether the child is gone: treat it as an unconfirmed exit. Only a spawn that never produced a child releases the slot at once.
- The runner's promise must always settle: give it its own watchdog (timeout plus grace plus a margin) so that a lost event cannot leave the queue waiting forever. Settling is not releasing: an unconfirmed kill settles the promise with that outcome and leaves the slot held as above.
Do not log untrusted text verbatim. The OWASP Logging Cheat Sheet says event data from a different trust zone "must always be treated as untrusted data," that an attacker who injects CRLF characters can "cause an additional log entry that looks like it came from a completely different user," and recommends sanitizing CR, LF and delimiters, structured formats such as JSON, and limits on value size. It lists data to keep out of logs, including session ids, access tokens, passwords, connection strings and keys. Apply this to the frame (log only the validated id) and to the command's output, which may contain text that originated in the market.
6.4 The worst case
If the channel is authenticated and these controls hold, the worst a forged or malicious push can do is cause one sync per cooldown period. That is a resource risk, not an execution risk, and it is the capability the poll already has. This is the practical meaning of push as a hint: it gives the server no new power over the agent, only a faster way to use a power it already has.
7. Keeping the poll as a backstop
7.1 Why it stays
Every layer between a change in the market and a completed sync can fail silently: the trigger, the fan-out, the network, half-open sockets, the parser. The poll is the one mechanism independent of push delivery, and it is what bounds staleness when that fails (under the conditions in 7.2). It is not independent of the execution path: with poll and push routed through one queue (section 5.3), a slot held by a child whose exit cannot be confirmed stalls both, which is why that state raises an alert rather than waiting silently. Removing it turns a push path that accelerates syncs into the only path. The sources that combine push and pull agree: FCM's overflow rule is push relying on pull for recovery; Dropbox cursors can expire and have a reset path; Kubernetes clients must tolerate 410 Gone and relist; Bowes names periodic reconciliation with the full state as a mitigation for edge-triggered weaknesses.
7.2 Choosing the interval
We found no authoritative number for a backstop interval. The rest of this subsection is our reasoning.
With the push path failing, staleness is bounded by the poll interval plus the sync duration only if the next eligible poll runs on schedule and completes a successful reconciliation. Each of these extends the delay: a poll whose sync fails (the next chance is another interval away, more with backoff); a poll that exits busy and has to retry (section 5.3); a poll that waits behind a sync already in flight; and the cooldown. So choose the interval from the staleness users can tolerate, with margin for those cases; alert on consecutive failed polls, since each one adds an interval; make a poll that finds nothing cheap; and do not lengthen the poll until you have measured how often pushes fail to arrive.
That measurement needs care. A poll that finds work is not by itself proof that a push was lost: the poll can run between the change and a push-triggered run that was delayed by the cooldown or coalesced into a follow-up, and find the work first. Treat poll-found-work as a signal to correlate with the trigger records (was a push for this change accepted, and when?) and with run outcomes (did the push-triggered run fail, time out or exit busy?). Only a change that no accepted push covered, or whose push-triggered run never reconciled, counts as a push-path failure.
7.3 Jitter on the agent side
The AWS Builders' Library says "If all the failed calls back off to the same time, they cause contention or overload again when they are retried," adds "Jitter isn't only for retries," and says the authors consider "adding some jitter to all timers, periodic jobs, and other delayed work." Clients that send requests on a regular interval "can line up and trigger their requests at the same time," such as "the first few seconds of a minute, or the first few seconds after midnight for daily jobs"; by working with clients to jitter their periodic workloads, the authors report that they "accomplished the same amount of work with less server capacity." For scheduled work they use "a consistent method that produces the same number every time on the same host," so load patterns are reproducible.
The Google SRE book advises: "Always use randomized exponential backoff when scheduling retries." It notes that as soon as crashed servers come back online "they're bombarded with an extremely high rate of requests and fail almost immediately," and, on understanding how large clients use a service, says you want to know whether they "Are vulnerable to external triggers that can create large amounts of load" (its example is an externally triggered software update that clears an offline client's cache). Discord's first heartbeat waits heartbeat_interval * jitter, with jitter a random value between 0 and 1; the docs say this offset "is meant to prevent too many clients (both desktop and apps) from reconnecting their sessions at the exact same time."
Our recommendations: jitter the poll (a random or per-host stable phase), the reconnect backoff (randomized, exponentially growing), and the open-triggered sync. After a server restart every agent reconnects and, by design, syncs; a small random delay before it spreads the wave. That one is easy to forget because the sync on every open was added for correctness and its load effect shows only at fleet scale; for a small fleet the extra parameter may not be worth it.
7.4 Server-side fan-out
A sync-now message sent to many agents at once converts a smeared load into a spike: the SRE book's external-trigger scenario. Mitigations, from the sources and our reasoning:
- Collapse per recipient. RFC 8030's
Topiclets a new message replace "any outstanding push message with an identical topic"; FCM's collapse key replaces a stored message that has yet to be delivered; Apple'sapns-collapse-idis "An identifier you use to merge multiple notifications into a single notification for the user," and APNs stores only one notification per bundle ID for a device it cannot reach, in most cases the latest. If the server queues sync-now messages for offline agents, keep at most one per agent. - Send in waves, spread over a window sized from market capacity and fleet size, and enforce a minimum interval per agent (Apple's two-or-three-per-hour guidance shows how a platform treats this).
- Shed load at the backend. The SRE chapter says servers should "fail early and cheaply" when overloaded and gives as an example dropping requests "for low-priority operations like background synchronization, but keep serving interactive user sessions." Treat the sync endpoint that way, and have the sync command honor a retry-after signal with backoff and jitter.
- Watch the receivers. Slack temporarily disables an app's event subscriptions when it enters failure conditions "for more than 95% of delivery attempts within 60 minutes." The WebSocket equivalent is to stop pushing to connections that do not acknowledge or keep reconnecting.
8. Failure handling and logging
8.1 Outcomes of a run
The queue must return to a consistent state, honoring the pending flag, whatever happens. A run satisfies the requests it covers only if it performed a reconciliation.
- Exit 0: success; a reconciliation ran.
- Non-zero: the run failed, and the requests it covered are not satisfied; keep the obligation and retry after the backed-off cooldown (8.3), not in a tight loop. Do not assume the state is unchanged: a command can fail after a partial write unless its own contract guarantees rollback. The reconcile must therefore be safe to rerun from a partial state, which a desired-versus-actual reconcile is if each of its steps is.
- Timeout: the 60-second limit fires and the escalation in section 6.3 runs. Treat it as failure. Release the running slot only once the child, and its process group where helpers exist, is confirmed gone; if that cannot be confirmed, hold the slot, start no new runs and raise an alert. The runner's own watchdog guarantees the outcome is always reported, so the queue never waits silently on a lost event; a silent wedge would make the agent stop reacting to pushes forever, the worst failure mode of this design.
- Busy: the command found another sync holding its lock (in the illustration, one started by the poll or by another process). Busy is not done: the running sync may already have read its inputs (section 5.3), so keep the pending flag and retry after the cooldown, backing off on repeated busy exits. It is not an error either: log it as its own class, without alarms. The simpler fix is to remove the case by routing the poll through the same queue. The exit-code contract between queue and command should be small, documented and tested.
- Spawn error: a missing binary or permissions problem is environmental, not transient; surface it loudly.
8.2 What to log
Log enough to answer why a sync ran and what happened, without recording untrusted content: for a rejected frame, a reason class (not for this agent, invalid id, unknown shape) and never the raw frame; for a duplicate or accepted request, the validated id and the queue state at arrival; for a run, its trigger (push, open, poll), request id, whether it was a follow-up, and at the end the exit code or signal, duration and outcome class (ok, failed, timeout, kill unconfirmed, busy); and, when a poll run finds work, enough to correlate it with the trigger records: the change it found and the most recent push requests and their run outcomes (section 7.2). Cap and sanitize the command's output per the OWASP guidance, keep tokens and keys out, and summarize repetitive rejections so a flood of bad frames does not become a flood of log lines.
8.3 Backoff on failure
Our suggestion: failed runs extend the cooldown (for example by doubling to a cap) and reset on success. The SRE book supports the principle with randomized exponential backoff and a retry budget.
9. Testing with fake clocks and injected events
The logic is a small state machine with timers, deterministic given a sequence of events and a clock. It can be tested exhaustively without real waiting.
9.1 Structure the code for it
Inject the clock (a now() and timer functions; the workqueue's Clock config field is the same idea), the process runner (a promise the test controls: resolve with an exit code, reject, never settle, or report that the child ignored a signal), and the events themselves (request("id-1"), open(), tick(ms)). The WebSocket layer is a thin adapter that parses, validates and calls request; test it separately with literal frames. Use a monotonic clock.
Node's test runner has mock timers; its documentation describes simulating and controlling "the behavior of timers, such as setInterval and setTimeout, without actually waiting for the specified time intervals," via mock.timers.enable() and tick(), with optional Date mocking, and notes that destructured imports such as import { setTimeout } from 'node:timers' are not supported. Any fake clock gives the same effect: a test of the 2-second cooldown takes microseconds.
9.2 What to test
Scenario tests that mirror the rules, plus one property test.
| Scenario | Expected |
|---|---|
| Request while idle | Run starts at once, no time advance |
| Request while running | No second run now; exactly one follow-up after the run ends |
| Request within the cooldown | No run until the cooldown ends; then exactly one |
| Back-to-back runs (cooled reading) | Gap of at least the cooldown between one run's end and the next start |
| Duplicate id | Ignored; pending flag untouched |
| 257th distinct id, or 10 min plus 1 ms | The evicted id is accepted again |
| Invalid id, wrong agent, extra fields | Invalid rejected without side effects; unknown fields ignored |
| Run times out at 60 s; child exits on SIGTERM | Slot released only after the exit event; a later request runs |
| Run times out; child ignores SIGTERM | No follow-up starts while the child is alive; after SIGKILL and confirmed exit, the pending follow-up runs |
| Run times out; exit never confirmed | Runner promise settles; slot stays held; no new run; alert raised |
| Run exits non-zero | Pending obligation kept; retry after the backed-off cooldown |
| Spawn fails (no child was started) | Slot released at once; pending flag still honored; error surfaced |
| Runner errors after a successful spawn (for example a control operation fails) | Treated as an unconfirmed exit: slot held until the child is confirmed gone; no new run meanwhile |
| Poll run has already read v41; push for v42 arrives; the push's command exits busy | The request stays pending; the queue's retry after the cooldown starts after the poll's sync releases the lock, reconciles and can see v42; the busy exit alone never marks it done |
| Repeated busy exits while a long sync holds the lock | Retries back off; no error alarm; the first non-busy successful run clears the pending flag |
The property test is the lost-update invariant. Generate random interleavings of request, open, tick, poll-started syncs outside the queue, and run completions with random durations and outcomes; run to quiescence with the command eventually succeeding; assert that every accepted request is followed by a run that starts at or after its arrival and actually performs a reconciliation (a busy exit, a failure or a timeout does not count), that at most one run is in flight and at most one queued, and (if you adopt the cooled reading) that no run starts within the cooldown of the previous end. With a fake clock, tens of thousands of schedules run in seconds.
9.3 What not to test in real time
Real waits prove nothing the fake-clock tests do not and make the suite slow and flaky. Real execution is needed only at the integration boundary: the actual command launched with the actual argv, no shell, a hung child (and a helper it started) killed through its process group. Cover that with a few tests against a stub executable, with the timeout and grace period shortened in the harness, not in the production default. Test the reconnect path with a scripted fake server (open, frame, drop, reopen), verifying one queued sync per open and reconnect delays driven by an injected clock and seeded random source.
10. Practical checklist
- Design: the push carries no state the agent acts on; the sync is idempotent and level-triggered, and safe to rerun after a partial failure; the poll stays, with an interval chosen from tolerable staleness plus margin for failed, busy and queued polls, and per-agent jitter; route poll, push and open through the same queue; every open (including the first after restart) enqueues one sync through it; each run records its trigger (
push,open,poll). - Frame handling: parse defensively, ignore unknown fields, require that the frame names this agent, validate the id by strict charset and length, reject without echoing the raw frame, dedupe by id (count bound plus time bound on a monotonic clock) before the queue.
- Queue: one run at a time; a boolean pending flag; at most one queued run; a request during a run always yields a run that starts after it and performs a reconciliation; leading-edge run when idle; trailing run after a burst; document and test whether the follow-up waits for the cooldown; release the running slot only after the child's exit is confirmed; the runner's promise always settles.
- Execution: fixed executable and argv, no shell, nothing from the frame in command, environment or files; output cap; timeout enforced on the process group (
detached: true,SIGTERM, grace period,SIGKILL), with an alert and no overlap if the kill cannot be confirmed; a small exit-code contract (success, failure, timeout, spawn error, and busy, which keeps the pending flag for a retry after the cooldown). - Logging: validated ids, decisions, trigger, exit class, duration; never raw frames or unbounded output; sanitize control characters; no secrets; rate-limit repeated rejections; when the poll finds work, log enough to correlate it with push records and run outcomes before calling it a push failure.
- Fleet: jitter the poll phase, reconnect backoff and (at scale) the open-triggered sync; server side, one pending sync-now message per agent, sends spread over a window, a per-agent minimum interval, load shedding at the sync endpoint.
- Tests: fake clock and injected events for every row in section 9.2, the lost-update property test, and a few stub-executable tests for no-shell and process-group timeout behavior.
11. What we would not do
- Trust the contents of a push. Do not read a package name, URL, version or command out of the frame, even from an authenticated server. If a later feature needs to sync one specific thing, pass a key from a closed set mapped to a fixed action, never free text.
- Queue every push. A pending flag keeps the obligation without counting.
- Drop or merge pushes that arrive during a run. Both are the lost-update window.
- Count a busy exit as done, or hand the request to the lock holder and forget it. It is the lost-update window one process level down.
- Release the running slot when the timeout fires, before the child and its helpers are confirmed gone.
- Skip the reconnect sync. Missed pushes are not redelivered and the next one may be far off.
- Add sequence-number replay without need.
- Remove the poll. It covers half-open sockets, trigger gaps and parser bugs, and what it finds, correlated with trigger records and run outcomes, shows where the push path loses signals.
- Use a shell or build the command line from the frame, even with escaping or an allowlist, when a fixed argv is available.
- Let a failing sync run at the cooldown rate forever, push to the whole fleet in one loop, or rely on real-time waits in tests.
12. Limits of this research
- Apple's documentation renders with JavaScript. We read "Pushing background updates to your App" and "Sending notification requests to APNs" from Apple's documentation data (JSON) for those pages.
- The Dropbox reference entry for
files/list_folder/longpollwas not retrievable; we rely on the Dropbox webhook and change-detection guides. Those guides give no threshold for disabling a failing webhook, so we state none. We did not verify the workqueue package's delaying and rate-limiting variants. - We found no verifiable first-party source for browser-level request coalescing and cite none.
- We found no authoritative number for a backstop interval, dedup window or cooldown. The figures in the illustration (256 ids, 10 minutes, 2 seconds, 60 seconds, five minutes) are the example's parameters, not any source's recommendation.
- The cooled follow-up, monotonic time, backoff on failure, jitter on the open-triggered sync, the rule that a busy exit leaves the request pending, and the process-group timeout contract (escalation, confirmed release, runner watchdog) are our own recommendations, reasoned from other systems' documented behavior. Node's documentation supplies the behaviors the timeout contract rests on, not the contract itself.
Sources
- Kubernetes client-go workqueue source: https://raw.githubusercontent.com/kubernetes/client-go/master/util/workqueue/queue.go
- Kubernetes API concepts (watch, resourceVersion, 410 Gone, bookmarks): https://kubernetes.io/docs/reference/using-api/api-concepts/ and https://raw.githubusercontent.com/kubernetes/website/main/content/en/docs/reference/using-api/api-concepts.md
- Level triggering and reconciliation in Kubernetes (James Bowes, quoting Joe Beda): https://hackernoon.com/level-triggering-and-reconciliation-in-kubernetes-1f17fe30333d
- Firebase Cloud Messaging, message lifespan and delivery: https://firebase.google.com/docs/cloud-messaging/customize-messages/setting-message-lifespan
- Firebase Cloud Messaging, collapsible and non-collapsible messages: https://firebase.google.com/docs/cloud-messaging/customize-messages/collapsible-message-types
- Apple, Pushing background updates to your App: https://developer.apple.com/documentation/usernotifications/pushing-background-updates-to-your-app
- Apple, Sending notification requests to APNs: https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns
- RFC 8030, Generic Event Delivery Using HTTP Push: https://www.rfc-editor.org/rfc/rfc8030
- RFC 6455, The WebSocket Protocol: https://datatracker.ietf.org/doc/html/rfc6455
- Dropbox webhooks: https://docs.dropboxapi.com/dropbox-api/docs/webhooks
- Dropbox, Detecting changes: https://docs.dropboxapi.com/dropbox-api/docs/detecting-changes
- Discord Gateway: https://docs.discord.com/developers/events/gateway
- Slack Events API: https://docs.slack.dev/apis/events-api/
- Slack Socket Mode: https://docs.slack.dev/apis/events-api/using-socket-mode/
- Stripe, Receive events in your webhook endpoint: https://docs.stripe.com/webhooks
- Stripe API reference, Idempotent requests: https://docs.stripe.com/api/idempotent_requests
- GitHub, Best practices for using webhooks: https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks
- GitHub, Handling failed webhook deliveries: https://docs.github.com/en/webhooks/using-webhooks/handling-failed-webhook-deliveries
- Lodash documentation,
_.debounceand_.throttle: https://lodash.com/docs/4.17.15 - CSS-Tricks, Debouncing and Throttling Explained Through Examples: https://css-tricks.com/debouncing-throttling-explained-examples/
- Go singleflight package: https://pkg.go.dev/golang.org/x/sync/singleflight
- Martin Fowler, What do you mean by "Event-Driven"?: https://martinfowler.com/articles/201701-event-driven.html
- AWS Builders' Library, Timeouts, retries, and backoff with jitter: https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter
- Google SRE Book, Addressing Cascading Failures: https://sre.google/sre-book/addressing-cascading-failures/
- Node.js
child_process: https://nodejs.org/api/child_process.html - Node.js test runner mock timers: https://nodejs.org/api/test.html#timers
- MITRE CWE-78: https://cwe.mitre.org/data/definitions/78.html
- OWASP Logging Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html
