Sub topic 16
Security, privacy, and rate limiting
This chapter assumes you know how WebSocket connections work, how the chat servers from earlier chapters are laid out, and the basics of HTTP authentication. It covers three things: who may connect, who may read a message, and how to stop one client from overwhelming the system.
Authenticate at the connection boundary
A WebSocket connection lives for hours, so authenticate once when it opens and tie the result to the connection. The usual flow is:
- The client logs in over HTTPS and receives a short-lived token.
- The client opens
wss://and presents the token, either in the first request or as the first frame. - The chat server validates the token and stores the user ID on the connection.
- Every later frame is treated as coming from that user. The client never sends its own sender ID that the server trusts.
Always use wss://, which is WebSocket over TLS. Plain ws:// exposes tokens and messages to anyone on the network path.
Tokens expire while connections stay open. Decide what happens then: either the client sends a refreshed token over the open connection, or the server closes it and the client reconnects.
Authorize every action
Authentication says who the user is. Authorization says what they may do. Check it on every send and every history fetch:
- Before accepting a send, confirm the sender is a member of the chat.
- Before returning history, confirm the requester is a member.
- Before fan-out, use the server's membership list, not a list supplied by the client.
A common mistake is to check membership only when the connection opens. A user removed from a group would keep receiving messages until they disconnect.
Protect data in transit and at rest
TLS protects data between client and server. Encryption at rest protects stored messages if a disk or backup leaks. Both are standard.
Neither stops the service operator from reading messages. End-to-end encryption (E2EE) does: only the sender's and recipients' devices hold the keys. The trade-off is that the server can no longer search messages, generate previews, or rebuild history for a new device without help from the client. Groups also need key management when members join or leave. Decide early whether E2EE is a requirement, because retrofitting it is hard.
Privacy
- Collect and retain only what you need. Set a retention policy for messages and logs.
- Support deletion. Remember that deleted messages may also exist in caches, search indexes, and backups.
- Keep message text out of application logs and push payloads where possible. A push notification passes through a third-party provider.
Rate limiting
Rate limiting caps how much work one client can request. Without it, a buggy client in a retry loop or a spammer can degrade service for everyone. A token bucket is a common approach. The bucket holds a limited number of tokens and refills at a steady rate. Each message spends one token. A full bucket allows short bursts, and the refill rate sets the long-run limit.
import time
class TokenBucket:
def __init__(self, capacity, refill_per_sec):
self.capacity = capacity
self.refill_per_sec = refill_per_sec
self.tokens = capacity
self.updated = time.monotonic()
def allow(self, now=None):
now = now if now is not None else time.monotonic()
elapsed = now - self.updated
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_sec)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
bucket = TokenBucket(capacity=5, refill_per_sec=1)
results = [bucket.allow(now=0) for _ in range(6)]
assert results == [True] * 5 + [False]
assert bucket.allow(now=2)Apply limits per user and per connection, and consider separate limits for messages, new connections, and group creation. If a user can connect to many servers, keep the counters in a shared store such as Redis, or accept that each server enforces its own approximate limit.
Retries from the earlier chapters interact with limits. When you reject a message, tell the client explicitly so it can back off instead of retrying at once.
Abuse control
Rate limits slow abuse but do not end it. Add the ability to block users, report messages, and restrict messaging from strangers. Spam detection can run asynchronously on the message stream so it does not add latency to delivery.
Exercise
A user is removed from a group chat but keeps receiving its messages until they close the app. Which check was missing, and where should it run?
Show answer
Authorization on fan-out (and on send and history fetch). Membership must be checked against the server's current membership list on every action, not only when the connection opens.
Exercise
A token bucket has capacity 10 and refills 2 tokens per second. A client sends 10 messages at once, then waits 3 seconds. How many messages can it send immediately after that?
Show answer
6. The bucket was empty after the burst, and 3 seconds of refill at 2 tokens per second gives 6 tokens.