DartAdvanced 2 min read

Dart WebSockets and background jobs: manage long-lived work

Define connection and job lifecycles without assuming an HTTP request owns every ongoing task.

On this page

A live dashboard and an export job have different lifetimes from one ordinary HTTP response. Choose a communication contract before adding timers and global stream controllers to a server.

WebSocket lifecycle

A WebSocket keeps a bidirectional connection open. Authenticate the connection through an appropriate server-controlled flow, validate each message and define permitted actions. Use bounded message sizes and an explicit close/reconnect policy. A connected socket is not proof that the user remains authorized forever.

For a local Dart client using web_socket_channel, the basic lifecycle is:

final channel = WebSocketChannel.connect(Uri.parse('ws://127.0.0.1:8081/events'));
await channel.ready;
try {
  channel.sink.add('{"type":"subscribe","topic":"tasks"}');
  await for (final event in channel.stream) {
    // Parse and validate each event before applying it.
  }
} finally {
  await channel.sink.close();
}

This is a client fragment requiring the package import and a real server implementing that protocol. The task REST starter does not expose this WebSocket route. Use secure transport outside local development and test connection loss and duplicate delivery explicitly.

Background work needs durable ownership

An invoice export may outlive its initiating HTTP request. Return a job identifier and store status in a durable job system when the work must survive process restarts. A Timer in a single service instance is not a reliable distributed scheduler.

Define retries, idempotency, a maximum attempt count and how failed jobs are inspected. Multiple workers must not apply a charge or send an irreversible action twice because a delivery was repeated. Keep provider-specific queue details behind an application interface.

Backpressure and cleanup

Decide what happens when a consumer is slower than incoming events. Unbounded buffering can become a memory problem. Close owned subscriptions and sockets on shutdown, and avoid keeping one controller alive forever after all consumers have left.

Exercise

Design task-updated events containing an ID and version, then explain how a reconnecting client refreshes missed state. Separately design an export-job state machine with pending, running, completed and failed states. Test each boundary without pretending a process-local timer is durable storage.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.