Video in progress

In a B2B SaaS, several customer companies share one real-time infrastructure. How do you ensure isolation and security between tenants?

The tenant identifier is taken from the token and added on the server as a mandatory prefix of every channel name; the client can't set it itself. On top of that you need per-tenant quotas, audit, and a key/rotation policy.

📖 Answer

The most dangerous mistake in a real-time system is a user from company A seeing company B's events. In REST this is normally checked on every request. In WebSocket the subscription happens once and then messages flow in, so the check at subscription time and the channel naming scheme are decisive.

The rules I rely on:

The tenant is added on the server. The client subscribes to /topic/orders. The server turns it into tenant.{tenantId}.orders, and tenantId comes from the token at CONNECT time. Even if the destination the client sent contains a tenant, it isn't trusted. Then the attack of "trying another tenant's name" is pointless.

On the publish side too. When backend services emit an event, they must take the tenant from the service context, not from the payload. If the channel name is assembled by hand in code, a mistake is easy. I hide it behind one library function and test for tenant mixing.

Revocation. A customer's contract ended or a user was deleted: all their open connections must be closed immediately. An event from the auth service, and the gateways find the sessions by tenant or user and close them. For this the gateway needs a tenantId -> sessions index.

Quotas and fairness. One large customer's burst of events mustn't wreck the others' latency. Message rate limits per tenant and separate queues. For very large customers, a dedicated gateway pool (a dedicated shard).

Audit. Who subscribed to which channel, when, and from which IP is the first thing asked in a security review. Logging every message is expensive, but storing subscribe and connect events is cheap and useful.

Data residency. Some customers require that data not leave a certain region. That means binding the tenant to gateways and brokers in that region, which has to be accounted for in the routing layer in advance.

I also have this checked with a penetration test: with two tenant accounts, try to subscribe to each other's channels and to send messages. It should stay in CI as an automated test.