
# 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

```dart
@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}');
});
```

```properties
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

- Each event's data is read like a JSON body, through the `ObjectMapper`. `EventStream<String>` gives the data as sent. An event that cannot be read arrives as an error on the stream (a `DecodeException`), and the stream goes on.
- The stream is cold: each listener opens its own connection. Cancelling the subscription (or `break` in `await for`) closes it.
- The request carries `Accept: text/event-stream` (`produces` changes it) and `Cache-Control: no-cache`.
- Interceptors run for every connection, so a refreshed token is used when the stream reconnects.
- `read-timeout` covers only the wait for the response headers; after that, the stream may stay quiet as long as it likes.
- `call-timeout` applies to establishing each connection, not to the life of the stream.
- `Stream<T>` works as a return type too (you get an `EventStream<T>`). `Future<EventStream<T>>` is rejected at startup: return the stream directly, it connects when someone listens.

## 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`:

- a `retry:` field from the server replaces the configured delay;
- a `204 No Content` ends the stream;
- an error status ends it with the `FeignException` of the `ErrorDecoder`, unless that exception is a `RetryableException`, which reconnects;
- a stream that cannot connect within `call-timeout` fails with `FeignCallTimeoutException` and does not reconnect;
- at `logger-level` `basic` and above, each reconnect is logged as `---> RECONNECTING ...`.

| 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:

```dart
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

- [Methods](methods.md)
- [Server-sent events in the web starter](../spring-boot-starter-web/streaming/sse.md)
- [Testing](testing.md)
