Server-sent events

A method that returns EventStream<T> reads a text/event-stream response: a long-lived answer over which a service pushes updates (order statuses, prices, progress). EventStream<T> is a Stream<T> of the decoded data; the whole events, with their id, event and retry fields, are available through .events. The stream reconnects by itself, as a browser's EventSource does.

Why

Polling a service every few seconds wastes requests and still arrives late. Server-sent events push each change as it happens, over plain HTTP. Spring Cloud OpenFeign cannot stream at all; here the same client interface covers it, with reconnection built in.

Example

@FeignClient('orders', url: r'${orders.url}')
abstract interface class OrdersClient {
  @GetMapping('/shops/{shop}/orders/events')
  EventStream<OrderEvent> events(@PathVariable() String shop);
}

// Only the data:
await for (final order in orders.events('neon')) {
  log.info(order.status);
}

// The whole events, when the id or event name matters:
orders.events('neon').events.listen((e) {
  log.info('${e.id} ${e.event}: ${e.data.status}');
});
spring.feign.client.config.orders.event-stream.reconnect=true
spring.feign.client.config.orders.event-stream.reconnect-delay=3s
spring.feign.client.config.orders.event-stream.max-attempts=10

How it reads

Reconnection

When the response ends or the connection breaks, the client connects again after a delay and sends the last event id in Last-Event-ID:

Property Default Meaning
event-stream.reconnect true Connect again after the connection ended or broke.
event-stream.reconnect-delay 3s, or the server's retry: The wait before connecting again.
event-stream.max-attempts no limit How many connections in a row may end without an event before the stream gives up.

Each under spring.feign.client.config.<name>. (or default).

Fallback

With a fallback, the fallback's stream takes over when the stream fails before its first event. Later failures reach the listener.

In tests

MockHttpTransport answers with events:

server
  ..when(HttpMethod.get, '/shops/neon/orders/events').respondEvents([
    ServerSentEvent({'id': 1, 'status': 'NEW'}, id: '1'),
  ])
  ..when(HttpMethod.get, '/shops/neon/orders/events').respond(204); // the reconnect: stop

In Spring (Java)

Spring Cloud OpenFeign cannot stream. Spring's own answer is Flux<ServerSentEvent<OrderEvent>> (or Flux<OrderEvent>) from WebClient or an @HttpExchange interface, with reconnection left to retryWhen. Here EventStream<T> folds the event wrapper into the stream and reconnects by itself; the event-stream.* properties are additions.

See also