A real-time group chat application that lets many users talk in one shared room. This builds directly on the earlier single-server version: the chat, the WebSocket protocol, the username rules and the SQLite persistence are all still here. What is new is that the application now runs as a cluster of three backends behind a load balancer that chooses between them based on how loaded they actually are.
| Requirement | Where |
|---|---|
| Backend deployed on the three allotted systems | deploy/deploy.sh, deploy/cluster.env |
| Clients reach only the load balancer | loadbalancer/ — the submitted URL |
| Performance-based dynamic backend selection | loadbalancer/balancer.go, Balancer.Pick |
| Switch away when load crosses a threshold | Balancer.Pick, -threshold flag |
| Detect and skip unhealthy backends | Balancer.probeLoop, markFailure / markSuccess |
| Optimised threshold | scripts/experiments.py sweep, plotted in the report |
| Shared persistent storage, no duplicates | backend/store.py — UUID primary key |
/message and /feed at exactly those paths |
backend/server.py, route_message / route_feed |
| Own load generator | loadgen/ |
| Plots of response time and utilisation of all 4 systems | scripts/plot_results.py, report/plots/ |
browser / load generator
|
one address, one port: the load balancer
|
+-------------v--------------+
| Sys1 |
| Load balancer :6000 |
| Shared message store :7000|
+------+------+-------+------+
| | |
+--------------+ | +--------------+
| | |
+----v----+ +-----v---+ +------v--+
| Sys2 | | Sys3 | | Sys4 |
| backend | | backend | | backend |
| :5000 | | :5000 | | :5000 |
+----+----+ +----+----+ +----+----+
| | |
+--------------------+---------------------+
|
every backend reads and writes the
same store, and subscribes to its
stream, so all three serve identical
chat history
No backend owns any chat data. A message posted to Sys2 is persisted by the
store on Sys1 and streamed back out to Sys3 and Sys4, so a browser connected to
any backend sees it immediately, and /feed returns the same document from all
three.
Both are served by the load balancer at exactly these paths.
Takes client-name and msg. JSON body, form-encoded body and query string
are all accepted, as are GET and POST, because the encoding used by the
grading load generator is not known in advance.
curl -X POST http://<load-balancer>/message \
-H 'Content-Type: application/json' \
-d '{"client-name":"alice","msg":"hello"}'{"status":"ok","message_id":"6f1c…","seq":41,"timestamp":"…","duplicate":false,"backend":"sys3"}Pass a message_id to make a retry idempotent. If you do not, the load
balancer assigns one before forwarding, so its own retries cannot duplicate a
message either.
Returns every message. ?limit=N returns only the most recent N.
{"count":2,"messages":[
{"seq":1,"type":"chat","message_id":"…","client-name":"alice","msg":"hello",
"username":"alice","content":"hello","timestamp":"…"}
]}Each message carries both client-name/msg and username/content, so the
assignment's vocabulary and the original frontend's both work unchanged.
| Route | Purpose |
|---|---|
GET /health |
backend liveness, including whether it can reach the store |
GET /metrics |
the load signal the balancer scores on |
GET /lb/status |
the balancer's full view: every backend's score and health |
GET /lb/health |
whether any backend is still serving |
GET /lb/config?threshold=… |
retune the threshold without a restart |
| WebSocket upgrade | the original chat, proxied to a chosen backend |
Round-robin is not used. Every backend reports its own CPU, memory, queue depth and service latency; the balancer combines them into one load score between 0 (idle) and 1 (saturated):
score = 0.45·cpu + 0.25·latency/200ms + 0.25·queue/16 + 0.05·memory
where cpu is the highest of the backend process's share of a core, the
machine's CPU, and load average per core — a single-threaded backend saturates
one core long before the machine looks busy.
The routing rule is then:
- A backend failing its health probes is never chosen.
- While the current backend's score is under the threshold, it keeps the traffic. Staying put is what keeps latency low while there is capacity.
- Once it crosses the threshold, the least loaded healthy backend takes over, provided it is better by more than the hysteresis margin — which is what stops the balancer oscillating between two equally busy backends.
- If every backend is over the threshold the least loaded one is used anyway,
and the event is counted, so saturation of the whole cluster is visible in
/lb/status.
Health is judged by polling /metrics every 300 ms: two consecutive failures
drop a backend out of rotation, two consecutive successes bring it back. A
request that fails mid-flight is retried on another backend, which is safe
because it carries the same message id.
Each lab system runs under a 512 MB limit. Mirroring the whole history in memory worked until about 250k messages, then the store was OOM-killed on startup — at which point every backend correctly reported itself unhealthy and the balancer returned 503 rather than serving wrong data.
The mirrors are now bounded windows (the store keeps 60k messages, each
backend 400k). SQLite still holds everything; anything older than a window is
read back from it. /feed is written out in chunks rather than assembled as
one object, and a backend whose window no longer covers the whole history
relays the feed from the store, which streams it compressed: messages
evicted from the store's window are folded into one running gzip stream, and
each feed response resumes that stream from a copy of the compressor state, so
no old message is ever compressed twice. The relay passes the gzip through to
the client, which halves the bytes crossing the wire on a large history.
Deduplication is unaffected: it has always been the UNIQUE constraint doing
the work, and the in-memory id table is only a fast path for recent retries.
The balancer additionally holds a feed gate: /feed responses stream only
while the bytes they have in flight fit inside a budget, so early in a chat's
life hundreds of small feeds stream at once while a huge history admits only a
few — measured at 2,500 users, this keeps the message route at p99 ≈ 44 ms
even as the feed grows past 100 MB. A feed that cannot start within the wait
limit is answered with an immediate 503 instead of joining a queue it would
time out in. -feed-slots caps the concurrency outright, -feed-budget
(256 MB by default) enables the byte-based admission (0 disables it), and
both are retunable on /lb/config.
Measured, not guessed:
| Change | Effect |
|---|---|
| Commit inline instead of on a worker thread | store write time 11 ms → 0.06 ms |
Batch writes into /append_batch |
936 → 2,540 messages/s to the store |
| Stop clamping the queue and latency terms | in-flight went from 120/0/0 to 41/39/40 |
| Compress evicted messages once, reuse per feed | a 500k-message feed no longer re-compresses per request |
| Relay feeds from the store gzipped | halved the bytes per relayed feed |
SQLite was never the bottleneck — it does 113k rows/s here. The 11 ms was the commit thread waiting on the GIL behind a busy event loop. Together these took the cluster from 855 to 1,289 req/s, p95 from 383 ms to 207 ms.
At 2,500 concurrent simulated users the message route stays perfect while the
history grows: 3,000+ requests/s with every /message succeeding and p99
≈ 44 ms, and past 900k messages the store keeps serving appends at p95 ≈
0.1 ms while the feed gate sheds the /feed demand the link cannot carry
rather than letting it take the cluster down.
The batching never delays a message: if no request is in flight it goes out immediately, and batching only gathers messages that arrive while an earlier request is still on the wire.
Every message has a UUID primary key. The store inserts with
INSERT OR IGNORE, so a message that arrives again — a client retry, a
reconnection, a balancer failover — collapses onto the row already there and
the response reports "duplicate": true with the original sequence number.
Verified with twenty concurrent retries of one id spread across all three backends: one row, one sequence number, three consistent replies.
cd loadbalancer && go build -o loadbalancer . && cd ..
cd loadgen && go build -o loadgen . && cd ..
scripts/local_cluster.sh start # store, three backends and the balancer
curl -X POST http://127.0.0.1:6099/message -d '{"client-name":"me","msg":"hi"}'
curl http://127.0.0.1:6099/feed
scripts/local_cluster.sh stopConnection details live in deploy/cluster.env. With ssh keys in place:
deploy/deploy.sh start # build, upload, restart everything, verify
deploy/deploy.sh status
deploy/deploy.sh logs
deploy/deploy.sh check # exercise /message and /feed through the balancercd chat-frontend && npm install && npm run devIt connects to the load balancer on the host that served the page; override
with VITE_CHAT_URL (see chat-frontend/.env.example).
The load generator models a variable number of users sending messages of random
length at random intervals, mixing /message writes with /feed reads, and
samples every system's utilisation on the same clock.
loadgen/loadgen -target http://<load-balancer> \
-users 200 -duration 90s -min-len 8 -max-len 280 \
-min-interval 20ms -max-interval 500ms -interval-dist exp \
-feed-ratio 0.2 -metrics "lb=…/lb/status,sys2=…/metrics,…"The experiments in the report are driven by:
venv/bin/python scripts/experiments.py all # main, sweep, scaling, failover, websocket
venv/bin/python scripts/plot_results.py # figures into report/plots/├── backend
│ ├── server.py chat backend: /message, /feed, WebSocket chat, /metrics
│ ├── store.py shared persistent store, deduplication, fan-out
│ ├── storeclient.py pooled client and streaming subscriber
│ ├── httpd.py small asyncio HTTP/1.1 server
│ └── sysmetrics.py CPU, memory and latency sampling from /proc
├── loadbalancer
│ ├── main.go flags, listener, TLS detection
│ ├── balancer.go load scoring, threshold policy, health probing
│ ├── proxy.go HTTP and WebSocket forwarding, retries
│ └── selfmetrics.go the balancer's own use of Sys1
├── loadgen/main.go the load generator
├── scripts
│ ├── local_cluster.sh run the whole cluster on one machine
│ ├── experiments.py the report's experiments
│ └── plot_results.py the report's figures
├── deploy
│ ├── cluster.env where the four systems are
│ └── deploy.sh build, upload, start, verify
├── chat-frontend React client
└── report LaTeX report, data and plots
Python (asyncio, websockets, SQLite), Go (standard library only for the load
balancer), React, Vite, matplotlib.