Docs

Sync Server & Client UI States

Technical details of how server to client communications work.

Server to client communications contain the synchronization tokens for communicating and UI state tracking. This tracking is meant for ordering messages. It’s also used to verify that both sides are in the same known state.

Synchronization Tokens

The syncId token marks the state of the server and is returned as received by the client. Whereas, the clientId token is incremented for each message sent by the client, with the server incrementing to match the next id in the response. Both syncId and clientId are integers.

syncId

The syncId holds the latest communication state identifier given by the server. It’s generated as a strictly increasing id for each response to every request from the client.

This identifier is replayed to the server on each request from the client. It helps the server to know the state of the client and to compare it against its own state.

The initial value when no response has been received from the server is UNDEFINED_SYNC_ID(-1). This is the value after the bootstrap HTML loading and before the first UI is rendered.

The syncId is always incremented by 1 after a new UIDL response is generated. The client then handles the received messages according to the syncId and the latest handled syncId, so that changes are handled in the correct order.

clientId

The clientId holds the latest communication state identifier given by the client. The client token is incremented on the client after sending the message, but only if the client has already received a response from the server to the previously sent message. Until this response has been received, the client attempts to resend the message until some kind of response is received, and the messages generated during that time are placed in a queue to wait. Once the server has received the message from the client, it increments the token value in the response to match the next expected clientId (i.e., client updated after message sent).

On the client, pending messages are removed from the queue as handled when clientId from server matches the next expected value. If the id is less than expected, the client waits since the server has not yet seen all messages. The response should arrive later. Otherwise, the client trusts the server and updates the id to the server’s expectations.

On the server, in cases where the id is the previous one with the same request payload, the server re-sends the latest response since the client probably didn’t receive the message. If the client-sent id doesn’t match the server-expected id, the server discards the message and the client shows a session synchronization error.

UI State Re-Synchronization

Re-synchronization occurs when the client detects that its state is no longer in sync with the server. This can happen due to unexpected network interruptions, or inconsistencies between the client-side UI and server-side state caused by misconfigured reverse proxies or session replication setups.

Several factors can lead to message loss or unexpected message identifiers:

  • Incorrect load balancer or reverse proxy configuration: Using setups without sticky sessions may result in receiving messages from the server which were meant for a different session or UI.

  • Firewall or Virtual Private Network (VPN) interference: Deep packet inspection can block certain packets.

These factors might also generate a delay in arrival of the messages. Virus scanners are particularly problematic and may cause issues when WebSocket_XHR is used. Increasing the maxMessageSuspendTimeout parameter value could help mitigate message arrival delays.

Other potential causes include:

  • Faulty router hardware: This could be due to routers using outdated firmware versions.

  • Unstable Wi-Fi or cellular connections: Fluctuating network conditions can disrupt communication.

  • Server-side issues: Request-handling hiccups may lead to inconsistencies, possibly due to server performance degradation.

Re-Synchronization Initiation & Mechanism

Re-synchronization is initiated by the client when it can’t find a message with the expected syncId among the pending messages from the server within a given timeout. The default is 5 seconds, which is configurable using the maxMessageSuspendTimeout parameter. Below is the process followed to re-synchronize:

Client Initiation:

  • The client clears the queue of pending messages from the server.

  • It terminates the current request and sends a re-synchronization request to the server.

Server Handling:

  • Upon receiving the re-synchronization request, the server invokes the detached listeners of UI components and re-attaches all components to the state tree.

  • The server then sends a response that includes the current UI state needed to rebuild the client-side state tree.

Client Update:

  • The client receives the updated UI state from the server.

  • It clears all old pending messages, updates the last known syncId to the newly received value, and rebuilds the DOM tree from scratch based on the server’s current state.

This process ensures UI consistency, even in the presence of errors or unexpected behavior. The application remains robust against transient network problems or client-side interruptions. Additionally, the user experience is preserved without requiring a full page reload, as Vaadin rebuilds the UI without reloading the entire bundle from the server.

Watching Requests and Messages from Page Scripts

window.Vaadin.Flow.clients[appId].events is an EventTarget that announces the requests the client sends to the server, the messages it receives from the server, and the UI stopping. A page script can follow a request or a message, for example to measure it. Heartbeats aren’t announced. The client engine dispatches on it but doesn’t listen to it, so a synthetic vaadin-request or vaadin-server-message that a page script dispatches changes nothing about what the client does. A synthetic vaadin-ui-terminated does have an effect: the Flow router listens to it to stop waiting for a pending navigation.

window.Vaadin.Flow.clients holds one client for each Vaadin application on the page, keyed by its application ID. A page that runs a single application can pick the client that has events, as the example below does. The client is added once the application has started, so run the script after that, for example from a view through Page.executeJs().

Listeners run synchronously inside the client’s own work, including while it queues invocations. Keep them cheap, and don’t call back into the client from them.

A vaadin-request event is dispatched when the first invocation for a request is queued, or right before the first send for a request that has no invocations, such as a resynchronization. Its detail is the request, which then dispatches events of its own as its delivery proceeds:

sent

An attempt to deliver the request goes out. The request’s attempt property counts attempts, starting at 0 while it’s still queued.

error

The attempt failed. The request’s failure property is an object whose reason says why: network, timeout, http, or invalid-response for a reply that couldn’t be parsed. For http, its status holds the HTTP status of the reply.

response

A reply to the attempt arrived and was identified.

end

The delivery has settled. The request’s outcome property says how: acknowledged for a reply from the server, rejected if the server couldn’t process the request or the session has expired, or discarded if the client gave up without a confirming reply. end is dispatched exactly once, as the last event.

The request is the same object across every attempt to deliver it. A resend after a lost connection, a resend from the resend timer, or a resend over a reconnected push channel all fire sent again on the same object, with attempt incremented.

Source code
JavaScript
const client = Object.values(window.Vaadin.Flow.clients).find((c) => c.events);
client.events.addEventListener('vaadin-request', ({ detail: request }) => {
  let sentAt;
  request.addEventListener('sent', () => (sentAt = performance.now()));
  request.addEventListener('response', () => console.log(`round trip ${performance.now() - sentAt} ms`));
  request.addEventListener('end', () => console.log(`request ${request.outcome}`));
});

A vaadin-server-message event is dispatched when data arrives from the server, before the client parses it. It covers both replies to requests and messages that the server pushes on its own. Its detail is the message, which then dispatches events of its own as the client handles it:

parsed

The message was parsed and identified. The message’s request property is the request it replies to. It’s undefined if the server sent the message on its own, or if the message repeats a reply to a request that the client no longer knows.

start

The client starts handling the message. Messages are handled in order, and this happens before the client loads the dependencies that the message brings.

end

The message’s outcome property says how it was handled: applied, discarded if the client dropped it without handling it, or failed if handling it threw an error, so it may be applied only in part. end is the last event. A message that couldn’t be parsed dispatches end without parsed or start. A message that the client never gets to handle, such as one waiting for a dependency that never loads, doesn’t dispatch end.

Source code
JavaScript
client.events.addEventListener('vaadin-server-message', ({ detail: message }) => {
  const arrivedAt = performance.now();
  message.addEventListener('end', () =>
    console.log(`message ${message.outcome} after ${performance.now() - arrivedAt} ms`));
});

A vaadin-ui-terminated event is dispatched when the UI stops, for example after an "Internal error" or "Session expired" reply, or after a communication error that the client doesn’t recover from. A page script that waits for a reply from the server can stop waiting, since the stopped UI doesn’t answer anymore. The stop isn’t always final: an embedded web component resynchronizes the session after "Session expired" and runs a new UI. The client’s isTerminated() method tells whether the UI is stopped at a given moment.

events is a full EventTarget, so a page script can also dispatch events on it, such as a synthetic vaadin-request or vaadin-server-message, to unit test its own listeners without a real request or message. The properties of a request or a message are read-only. Dispatching an event on one from outside the client reaches only its listeners — it changes nothing about the request, the message, or the client.

Triggering a Server-Side Task After a Delay

The UI.triggerAfter(Duration, SerializableRunnable) method runs a task on the server after a given delay, without enabling server push.

The delay is measured by the browser: a one-shot timer is armed on the client when the response to the current request is sent, and when the timer elapses, the client makes a round trip back to the server that runs the callback. The task runs in the same way as any other event handler, with the session locked. This makes it possible to defer a single piece of server-side work without configuring push for that purpose alone.

Source code
Java
Span status = new Span("Saved");
add(status);

// Hide the status message after five seconds
Registration registration = UI.getCurrent()
        .triggerAfter(Duration.ofSeconds(5),
                () -> status.setVisible(false));

The returned Registration cancels the task by clearing the client-side timer, so a task that’s cancelled before its delay elapses doesn’t run. A cancellation that races an already-elapsed timer, whose round trip is in flight, may still run once.

Because the timer lives in the browser, the task isn’t run if the page is reloaded, navigated away from, or closed before the delay elapses.

triggerAfter() must be called while holding the session lock, that is, from a regular event handler or from inside UI.access(). The same applies to calling Registration.remove() on the returned registration.

Updated –