Communication in system design, part 2: Kafka or RabbitMQ, real-time push and a fraud detection case study
Choosing Kafka or RabbitMQ for asynchronous communication (filling in what usually gets left out), four ways for a server to push data to clients (polling, long polling, SSE, WebSocket), MQTT for millions of devices and order books, QUIC stated correctly, and a full case study: designing a payment fraud detection system in 45 minutes.
On this page
1. The problem
A football app uses WebSocket for 1 million viewers. One gateway node dies during a goal, 200,000 clients reconnect in the same second, and the whole cluster falls over.
2. Key idea
Two different questions: which broker do backends talk through, and how does the server push to clients. Pick the simplest thing that's enough.
| Choice | Use when | Don't use when |
|---|---|---|
| Kafka | event streaming, high throughput, replay, many independent consumers | you need complex routing, delays, priorities |
| RabbitMQ | work queues, routing keys, TTL, dead letters | you need to keep and replay events long term |
| Polling | sparse updates, N seconds of delay is fine | you need real time |
| SSE | one way: notifications, prices, job progress | the client sends constantly |
| WebSocket | two way: chat, games, co-editing | you only receive; you don't want connection state |
| MQTT | broadcasting to many weak devices, IoT | a few simple web clients |
SSE is plain HTTP and browsers reconnect on their own; WebSocket handles heartbeats, auth and reconnects itself. A gateway layer only holds connections, listens to Kafka or Redis pub/sub and pushes to the right client.
2.1 Case study: payment fraud detection
50 million transactions/day, peak ~3,000 TPS, p99 < 100 ms for the risk check.
- Synchronous: Payment calls the Risk API over gRPC with a 100 ms deadline; features are precomputed in Redis, rules live in memory, it returns
ALLOW,REVIEWorDENY. - Asynchronous: events go through Kafka; chargebacks weeks later become training labels.
- When it fails: conditional fail-open: small transactions pass, large ones get OTP or 3-D Secure, and get rescored later.
3. In Java
A velocity counter: how many transactions a card made in the last hour, with a sorted set (an exact sliding window).
// Run in a pipeline or Lua script to keep one round trip
String key = "vel:card:" + cardFingerprint + ":1h";
long now = System.currentTimeMillis();
redis.zadd(key, now, transactionId); // add the current transaction
redis.zremrangeByScore(key, 0, now - 3_600_000); // drop what's outside the window
long countLastHour = redis.zcard(key); // 7
redis.expire(key, 3_700); // unused cards expire on their own
if (countLastHour > 10) return Decision.REVIEW;Other languages: the same Redis commands in Go (go-redis) and Node.js (ioredis).
Kafka, RabbitMQ, MQTT and QUIC: commonly misstated points
- Kafka has exactly-once through the idempotent producer (on by default since Kafka 3.0) and transactions, but only within Kafka.
- RabbitMQ can keep messages too: RabbitMQ Streams (since 3.9) is a replayable log; quorum queues replace mirrored queues.
- Often-quoted numbers (Kafka ~10 million, RabbitMQ ~500 thousand messages/second) are orders of magnitude for a whole cluster, not a single node.
- MQTT QoS: 0 may lose, 1 may duplicate, 2 is exactly once and slowest. Retained messages give new subscribers the current state; last will announces a device going offline.
- Order books aren't pushed whole: a snapshot with a sequence number, then only diffs; a sequence gap means reloading the snapshot; updates are conflated every 100 ms.
- QUIC doesn't "resend lost TCP packets": it runs on UDP and resends data for the affected stream only, so one lost packet only slows that stream.
4. Working with AI
Hand to AI: SSE or WebSocket gateways, Kafka consumers, a Lua script for the counter, connection-count load tests.
Check in AI-written code:
- Consumers that write to a DB or call external APIs are idempotent, even with Kafka's exactly-once on.
- One-way push uses SSE, not WebSocket.
- Client reconnects use backoff with jitter; the server rate limits the handshake.
- The load balancer's idle timeout is longer than the heartbeat interval.
- The synchronous path has a deadline and documented behaviour when it expires.
5. Exercises
Exercise 1: Pick a push mechanism
Choose polling, SSE, WebSocket or MQTT and explain: (a) an unread notification count on the web; (b) a document many people edit together; (c) a live football score for 1 million app viewers.
Solution to Exercise 1
- (a) SSE, or polling every 30–60 seconds for maximum simplicity: one way, small, a few seconds of delay is fine.
- (b) WebSocket: two way and continuous, each keystroke a small message. Add OT or CRDTs to merge edits, and put everyone on the same document on the same pub/sub channel.
- (c) MQTT or SSE through a fan-out layer: a broadcast problem. Conflate updates every few seconds; reconnect with jitter to avoid a reconnect storm when a goal is scored.
Exercise 2: Choose what happens when the Risk API fails
The AI wrote Payment to call the Risk API and return DENY on deadline expiry, "to be safe". Evaluate it, propose an alternative, and say when DENY is right.
Solution to Exercise 2
Fail-closed blocks legitimate transactions too: 5 minutes of a slow Risk API is 5 minutes of lost revenue. Pure fail-open lets fraudsters exploit exactly the outage window.
Alternative: conditional fail-open. Minimal fallback rules run locally (limits, a local deny list); small transactions pass, large ones get REVIEW or OTP; record the event for async rescoring; alert when the timeout rate climbs.
DENY is right when the risk of one transaction outweighs the lost revenue: high-value transfers, brand-new accounts, a market under active attack.
Summary
- Kafka for replayable event streams; RabbitMQ for flexibly routed queues.
- Kafka's exactly-once is Kafka-only; consumers must still be idempotent.
- One-way push uses SSE; only two-way needs WebSocket.
- WebSocket needs heartbeats, jittered reconnects, and gateways separate from business services.
- Fraud: a short synchronous path, an async path, conditional fail-open.
Read more: Calling an LLM from the backend.
Practice interview questions on this topic
- How do HTTP and WebSocket differ, and when should you use WebSocket?
- How do polling, long polling, SSE and WebSocket differ, and how do you push realtime updates to a huge audience?
- How do Kafka and RabbitMQ differ fundamentally, and what criteria do you use to choose a message broker?
All Web & REST API questions →All Messaging & Kafka questions →
Comments
Community rules