Agent Wranglers

API-69Recommended

Choose the transport that the feature needs

Poll when a delay of 30 seconds or more is fine. Use server-sent events when only the server sends. Use WebSockets only when the client also sends a stream of messages.

How to do it

Polling is a plain GET, so caching, rate limits and logs work as for any request. Server-sent events are one long HTTP answer that the browser reconnects and resumes on its own. Their format is in stream in a standard format. A WebSocket is a separate protocol with its own framing, so every limit and check must be built again. Choose it for chat, shared editing or games, where the client sends many small messages. Write the choice and its reason in the contract for each live feature.

Examples

JavaScript example

const events = new EventSource('/v1/orders/events');
events.addEventListener('order.shipped', event => {
  const order = JSON.parse(event.data);
  showShipped(order.orderId);
});

Python example

import json
from starlette.responses import StreamingResponse

async def order_events(request):
    async def stream():
        async for event in subscribe(request.user.shop_id):
            yield f"id: {event.id}\nevent: {event.type}\ndata: {json.dumps(event.data)}\n\n"
    return StreamingResponse(stream(), media_type="text/event-stream")

How to check

Each live endpoint in the contract names its transport and the reason. Each WebSocket endpoint lists at least one message type the client sends after it connects.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/live-connections/choose-transport">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.