Why WebSockets need a different runtime
Traditional PHP-FPM requests are short-lived: the process handles a request and returns a response. A WebSocket connection remains open, so it should generally be handled by a dedicated long-running server or managed realtime service rather than tying up ordinary PHP-FPM workers.
Separate application events from delivery
The PHP application should authorize an action and publish a small event to a broker or realtime gateway. The WebSocket service delivers the event to authenticated connections. This separation allows the web application and connection service to scale independently.
Authenticate the connection
Use a short-lived signed ticket or another provider-supported mechanism. Avoid putting long-lived bearer tokens in query strings because URLs may appear in logs. Validate the connection origin where browser clients are involved, and authorize each subscription to a channel or resource.
Design for disconnection
Networks drop. Clients should reconnect with backoff and refresh credentials when necessary. Events may be missed while disconnected, so provide a way to fetch current state or resume from a sequence number. Do not assume WebSocket delivery is a durable message queue.
Scale across instances
When multiple WebSocket servers run, use a shared pub/sub layer or broker so an event published by one PHP instance can reach clients connected to another. Monitor connection count, memory, heartbeat failures and outbound queue size.
Checklist
- Use a dedicated long-running WebSocket service.
- Keep PHP-FPM request handling separate.
- Authenticate connections and authorize subscriptions.
- Avoid long-lived tokens in URLs.
- Support reconnect and state resynchronization.
- Use shared pub/sub for multiple instances.
- Apply message size and rate limits.