Sub topic 16
Security, Privacy, and Rate Limiting
This chapter covers how to protect a chat system from outsiders, from abusive users, and from its own operators. It assumes you have read the earlier chapters on the WebSocket connection layer, the message flow, and presence. You should be comfortable with HTTP headers, tokens, and basic Python.
Where the threats are
A chat system has several trust boundaries. Each one needs its own control.
| Boundary | Threat | Main control |
|---|---|---|
| Client to edge | Eavesdropping, token theft | TLS, short-lived tokens |
| Connection setup | Impersonation, cross-site hijacking | Authentication at handshake, Origin check |
| Message send | Spam, flooding, oversized payloads | Rate limits, size limits |
| Conversation access | Reading chats you do not belong to | Per-message authorization |
| Storage | Data leak from a stolen disk or backup | Encryption at rest, retention rules |
| Media | Malware, hostile files | Scanning, separate domain |
The rest of the chapter follows this table from top to bottom.
Transport security and authentication
Every connection uses TLS. For WebSocket, that means wss:// and never ws://. TLS stops anyone on the network from reading or changing messages in transit. It is usually terminated at the load balancer or edge proxy, and traffic inside your network should also be encrypted if your threat model includes a compromised internal network.
Authenticate once, at connection setup, not on every message. The common flow is:
- The client logs in over HTTPS to a stateless API and receives a short-lived access token (for example, 15 minutes) and a longer-lived refresh token.
- The client opens the WebSocket and presents the access token.
- The connection server validates the token, binds the connection to a user ID and device ID, and keeps that binding in memory.
Browsers cannot set custom headers on a WebSocket handshake. You have three options for passing the token:
- A cookie, which the browser sends automatically. This requires CSRF-style protection (see below).
- A query string parameter such as
?token=.... This is simple but the token can end up in proxy and access logs. - A first message after the connection opens, such as
{"type": "auth", "token": "..."}. The server must close connections that do not authenticate within a few seconds.
Token expiry on long-lived connections
A WebSocket may stay open for hours, longer than the token's lifetime. Decide what happens at expiry. A workable rule is that the client sends a fresh token over the open connection before the old one expires, and the server closes the connection if it does not. This also gives you a way to revoke access: when a user is banned or a device is removed, the next refresh fails and the connection closes. For immediate revocation, publish a "disconnect user" event that every connection server subscribes to.
Authorization on every action
Authentication says who the user is. Authorization says what that user may do. The most common chat security bug is checking the first and forgetting the second.
On every send, the server must confirm that the sender is a member of the target conversation. On every history fetch, it must confirm the same for the reader. Never trust a chatId or senderId supplied by the client without checking it against the authenticated identity.
def authorize_send(user_id, chat_id, members_by_chat):
members = members_by_chat.get(chat_id)
if members is None:
return False
return user_id in members
members_by_chat = {"c1": {"alice", "bob"}}
assert authorize_send("alice", "c1", members_by_chat)
assert not authorize_send("mallory", "c1", members_by_chat)
assert not authorize_send("alice", "missing", members_by_chat)Two details matter here. First, use the user ID from the authenticated connection as the sender, and ignore any senderId field in the payload. Second, membership can change while a connection is open. If a user is removed from a group, the server must stop delivering that group's messages to the user's open connections. A cached membership list needs an invalidation path, not only a time-to-live.
Rate limiting
Rate limiting caps how much a user, device, or IP address can do in a period of time. In a chat system it protects against spam, scripted floods, and accidental client bugs such as the retry loop from the delivery chapter running without a back-off.
Token bucket
The token bucket is the usual algorithm. A bucket holds up to capacity tokens and refills at rate tokens per second. Each message costs one token. If the bucket is empty, the message is rejected. A full bucket allows a short burst, and the refill rate sets the long-term average.
import time
class TokenBucket:
def __init__(self, capacity, rate):
self.capacity = capacity
self.rate = rate
self.tokens = capacity
self.updated = None
def allow(self, now=None):
now = now if now is not None else time.time()
if self.updated is not None:
elapsed = now - self.updated
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
bucket = TokenBucket(capacity=5, rate=1)
results = [bucket.allow(now=0) for _ in range(6)]
assert results == [True] * 5 + [False]
assert bucket.allow(now=2)This allows a burst of 5 messages, then about one per second.
Where to enforce limits
Limits apply at several layers, with different keys.
- Connection attempts, per IP. Enforced at the edge. This limits login guessing and reconnect storms.
- Messages sent, per user and per device. Enforced on the connection server, which already holds the connection in memory, so a local bucket is cheap.
- Messages per conversation. Stops one group from flooding its members.
- Expensive operations. Creating groups, adding members, and searching users get stricter limits than plain sends.
A local bucket on each connection server works when a user is pinned to one connection. If a user can have several devices on different servers, you need a shared counter, usually in Redis. Keep the check atomic, for example with a Lua script, so that two servers do not both approve the last token. Decide what happens if the shared store is down. Failing open keeps chat working but removes protection. Failing closed protects the system but blocks all users. Many systems fall back to a coarse local limit.
What to do when a limit is hit
Do not silently drop messages. Send an explicit error frame with a code such as rate_limited and a retryAfterMs value, so the client can show a message and slow down. Repeated violations can escalate: a temporary mute, then a disconnect, then an account review. Also cap frame size (for example 64 KB for text), the number of frames queued per connection, and the number of connections per user. Without a cap on queued frames, a slow client can make the server hold unbounded memory.
Input validation and abuse control
Treat every field from the client as untrusted.
- Validate message type, length, and encoding before doing any work.
- Never insert message text into HTML on the client without escaping. Use
textContentinstead ofinnerHTML, or a vetted renderer. Stored cross-site scripting through chat messages is a classic bug. - Use parameterized queries for any database access.
- Reject duplicate
clientMsgIdvalues as retries, not as new messages, as described in the delivery guarantees chapter. This also stops an attacker from inflating storage by replaying one message.
Abuse control goes beyond rate limits. Provide block and report features, let users control who can start a conversation with them, and run spam detection on signals such as many first messages to strangers, repeated identical text, or links to known bad domains. Run these checks asynchronously where possible so they do not add latency to the send path.
Privacy and encryption
There are two levels of message protection.
Encryption in transit and at rest. TLS protects messages on the wire. The server still sees plaintext, stores it, and can search or moderate it. Disk or database encryption protects against stolen drives and backups. It does not protect against a compromised application server or a malicious operator.
End-to-end encryption (E2EE). Only the sender's and recipients' devices hold the keys. The server stores and relays ciphertext it cannot read. Protocols such as Signal's use per-device keys and key ratcheting, so a leaked key exposes only a few messages.
E2EE changes the rest of the design:
- Server-side search and spam scanning on message text are no longer possible. Search must run on the device, and abuse reports must include the reported messages sent by a user.
- Multi-device sync needs a way to deliver each message encrypted to each device, or to transfer keys securely between devices.
- Group chat needs key management when members join or leave.
- Push notification payloads cannot contain the message text. They carry only a "new message" signal, and the app decrypts after waking.
Choose E2EE when the product promises privacy and you accept these costs. A workplace chat tool that must support compliance search and legal hold usually cannot.
Data minimization and retention
Store only what you need. Define retention for messages, media, and logs, and delete on schedule. Support account deletion that removes messages the user owns, with a defined rule for what remains in other users' history. Do not log message bodies, access tokens, or push tokens. Log IDs and event types instead.
Media safety
Uploaded files are untrusted. Give each upload a size cap and a type check based on file content, not just the extension. Scan for malware, serve media from a separate domain so a hostile file cannot read your app's cookies, and use short-lived signed URLs so a leaked link stops working. Strip location data from images if privacy requires it.
Exercise
A user is removed from a group while their phone still has an open WebSocket. The server keeps a cached membership list for each group with a 10-minute time-to-live. What problem can this cause, and how do you fix it?
Show answer
The removed user keeps receiving the group's messages, and may still be able to send, until the cache entry expires. Fix it by invalidating or updating the cached membership immediately when the removal happens, for example by publishing a membership-change event that every connection server handles. Connection servers should also stop delivering to that user's open connections for that group and re-check authorization on each send and fetch.
Exercise
A token bucket has capacity 10 and a refill rate of 2 tokens per second. A client has been idle for a long time, then sends 25 messages in one second. Roughly how many are accepted, and what is the sustained rate afterward?
Show answer
About 12 are accepted: 10 from the full bucket, plus about 2 refilled during that second. The rest are rejected. Afterward the sustained rate is 2 messages per second, the refill rate.
Exercise
Why must the server ignore a senderId field sent inside a message payload?
Show answer
The client controls the payload, so a malicious client could set another user's ID and impersonate them. The server should take the sender identity from the authenticated connection instead.