Skip to content

Choosing Technologies: Communication, Caching, Messaging, Compute

Intermediate 55 min read Part 16 of 18

How to pick APIs, realtime transports, caches, queues and compute: REST vs gRPC vs GraphQL, queues vs streams, Kafka vs SQS, serverless, build vs buy.

Summary#

Every box on a system design diagram is a technology choice: how clients talk to servers, how services talk to each other, where hot data is cached, how work is queued, and where code runs. This page is a decision guide for the four families of choices besides the database (which has its own guide):

  • Communication. REST, gRPC or GraphQL for request/response; polling, Server-Sent Events (SSE), WebSockets or WebRTC for realtime.
  • Caching. Redis or Memcached, and where in the request path a cache belongs.
  • Messaging. A queue or a stream; Kafka, RabbitMQ, SQS and their relatives.
  • Compute. Virtual machines, containers or serverless functions, and whether to build a component or buy it.

The core method is the same in every family:

  1. State the requirement as a property. "Users see new bids within a second" is a push-latency property; "jobs must survive a worker crash" is a durability-and-acknowledgment property.
  2. Map the property to a category. Push latency → SSE or WebSockets; durable acknowledged work → a message queue.
  3. Pick the most boring product in that category that your team can operate, unless a specific requirement rules it out.
  4. Write down what would change your mind.

Sensible defaults cover most systems: REST with JSON for public APIs, gRPC between internal services when performance matters, polling or SSE before WebSockets, Redis for caching, SQS or RabbitMQ for task queues, Kafka for event streams, containers for long-running services and functions for spiky or event-triggered work. Most of the skill lies in knowing when a default doesn't fit, and in saying so with a reason.

Why It Exists#

Technology choice is where many designs go wrong. They don't go wrong because the chosen tools are bad. They go wrong because the tools don't match the requirement, or the team can't operate them. Two failure modes recur:

  • Over-engineering. WebSockets for a leaderboard that refreshes every five seconds, Kafka for a few hundred jobs per hour, a service mesh for three services, GraphQL for an internal API with one client. Each adds infrastructure, failure modes and on-call load without solving a real problem.
  • Under-engineering. Polling a database every second for a chat app with millions of users, an in-memory queue with no durability for payment jobs, or synchronous HTTP chains six services deep where any slow hop stalls the user.

Both come from choosing by habit or fashion instead of by requirement. A decision guide replaces both with a short chain of reasoning you can say out loud: this requirement → this property → this category → this product, because…

In interviews the stakes are compressed. Interviewers listen for whether you justify each technology. "We'll use Kafka" earns little; "Clicks arrive at 10,000 per second and three consumers need them independently, with replay after a bug, so a log like Kafka fits better than a task queue" shows judgement. Jumping into WebSockets without a stated need is a classic negative signal, because it shows a solution looking for a problem.

There's also a longer-term reason. Every technology you adopt is a commitment: someone must patch it, monitor it, upgrade it, understand its failure modes at 3 a.m., and teach it to new hires. Dan McKinley's essay Choose Boring Technology (2015) frames this as innovation tokens: an organisation can afford only a few novel technologies, perhaps three, so it should spend them where they create a real advantage and use proven, well-understood tools everywhere else. "Boring" here means the failure modes are known, not that the tool is weak. PostgreSQL, Redis and Kafka are boring in exactly this sense.

How It Works#

The decision method#

Every technology decision on this page follows the same four filters, in order:

  1. Fit. Does the category's core property match the requirement? A task queue gives per-message acknowledgment; a log gives replay and many independent readers. If the property doesn't match, nothing else matters.
  2. Team and organisation. What does the team already run well? An existing, well-operated RabbitMQ beats a theoretically better new system. Hiring, documentation and internal expertise all count.
  3. Operational cost. Who runs it, and at what cost in money and attention? Managed services trade money and some flexibility for far less operational work.
  4. Maturity and ecosystem. Client libraries in your languages, observability integrations, known failure modes, a community that has already hit your problem.

The method sounds obvious, but it disciplines two habits. It forces you to name the property before the product, which rules out fashion-driven choices. And it makes "what we already run" an explicit step rather than an afterthought. In interviews you can compress the whole chain into one sentence per box.

Communication: REST vs gRPC vs GraphQL#

Three API styles cover nearly all request/response communication. API Styles: REST, gRPC, GraphQL and More covers their mechanics; here is how to choose.

REST models the system as resources (users, orders, events) manipulated with HTTP methods: GET /events/42, POST /bookings, PATCH /bookings/7. Payloads are usually JSON. Its strengths are universality and simplicity. Every language, browser, proxy, cache and debugging tool understands HTTP and JSON. HTTP caching (Cache-Control, ETag) works for free on GETs, and a CDN can cache public responses. Its weaknesses are verbosity and fixed response shapes. JSON is text, repeating field names in every object, so it is larger and slower to parse than binary formats. And each endpoint returns a fixed shape, so clients either under-fetch (one call for a list, then one call per item: the N+1 round-trip problem) or over-fetch (bloated responses designed for every possible client).

A common modelling mistake is to think in operations rather than resources. POST /startGame and POST /updateUser are RPC calls in REST clothing. RESTful versions are PATCH /games/{id} with {"status": "started"} and PUT /users/{id}. Your design's core entities usually map straight onto resources. REST is the right default for public APIs and is perfectly fine internally until a specific need appears.

gRPC is a remote procedure call framework, open-sourced by Google in 2015, that runs over HTTP/2 and encodes messages with Protocol Buffers (protobuf). You define services and messages in a schema file. A compiler generates typed client and server code for many languages, so a call looks like a local function call (client.GetSeatMap(req)) and type errors are caught at compile time rather than in production.

Protobuf replaces field names with small numeric tags and encodes integers as variable-length bytes. Take a seat record {"seat_id": 1042, "row": "K", "price_cents": 8500}. As JSON it is about 50 bytes. As protobuf it is about 10: one tag byte plus a two-byte varint for each integer, and a tag, a length byte and one character for the string. Parsing binary is also much cheaper on CPU than parsing text.

HTTP/2 multiplexes many concurrent calls over one connection. gRPC adds streaming (client, server and bidirectional), deadlines that propagate across service hops, cancellation and pluggable load balancing.

The costs: browsers can't speak native gRPC, so browser clients need gRPC-Web through a proxy, or a REST/JSON gateway. Binary payloads are harder to inspect with everyday tools. And long-lived HTTP/2 connections confuse simple connection-level (L4) load balancers (see the Deep Dive). gRPC fits internal service-to-service traffic, especially high-volume, latency-sensitive calls, polyglot fleets that benefit from generated clients, and streaming between services.

GraphQL, open-sourced by Facebook in 2015, exposes a single endpoint and a typed schema of the whole data graph. Clients send queries naming exactly the fields and nested relations they need, and receive exactly that shape. One round trip can fetch a user, their last ten orders and each order's shipping status, with no over- or under-fetching. This shines when many clients with different needs (iOS, Android, web, partners) read overlapping data, and when frontend teams iterate faster than backend teams can add endpoints. GitHub (whose public API v4 is GraphQL) and Shopify (whose Admin API is GraphQL) are well-known public examples.

The costs move to the server:

  • Resolver execution. Naive resolvers cause N+1 database queries: one query for the list, then one per item for each nested field. The fix is batching with a DataLoader-style layer.
  • Arbitrary queries. Clients can send deeply nested, very expensive queries, so you need depth limits, cost analysis or persisted (allow-listed) queries.
  • Caching. Queries usually go over POST to one URL, so HTTP and CDN caching don't work out of the box.
  • Observability and authorization. Both are per-field rather than per-endpoint.

In interviews, GraphQL's benefits are often murky. The requirements are fixed and the interviewer wants to see how you optimise specific queries, so a resolver layer mostly gets in the way. Bring it up when the problem stresses client flexibility or rapidly changing frontend requirements, or when an aggregation layer (backend-for-frontend) for many client types is the real topic.

REST + JSONgRPC + protobufGraphQL
ModelResources and HTTP verbsTyped procedures (services and methods)Typed graph; client-shaped queries
PayloadText JSON, largerBinary, several times smallerJSON response, request is a query
TransportHTTP/1.1 or HTTP/2HTTP/2 (HTTP/3 emerging)Usually HTTP POST; subscriptions over WebSockets
Browser supportNativeNeeds gRPC-Web proxy or gatewayNative
HTTP/CDN cachingWorks naturally for GETsNot applicableHard; needs persisted queries or client caches
ContractsOpenAPI, optionalSchema required; code generatedSchema required; introspection
StreamingNot native (use SSE or WebSockets)Built in, bidirectionalSubscriptions
Best fitPublic APIs, simple CRUD, default choiceInternal high-volume service calls, polyglot microservicesMany diverse clients over overlapping data; BFF layers
Main riskOver- and under-fetching, chatty clientsL4 load balancing, debugging, browser gapExpensive queries, N+1 resolvers, caching

A widely used combination is REST at the edge and gRPC inside. Public clients get a stable, cache-friendly, debuggable HTTP/JSON API through an API gateway. Internally, services call each other over gRPC with generated clients and deadlines. Using REST everywhere is a perfectly acceptable interview answer too. Hyper-optimising the RPC protocol before addressing the real bottlenecks is premature optimisation.

Two older or adjacent styles still appear:

  • SOAP: XML messages with a formal WSDL contract and WS-* standards for security and transactions. You'll meet it integrating with banks, insurers, governments and older enterprise systems, but you won't choose it for new designs.
  • Webhooks: server-to-server callbacks, where you call the client's URL when something happens (Stripe calls your endpoint when a payment succeeds). They replace a partner polling your API. Design them with signatures (an HMAC of the body under a shared secret), retries with backoff, idempotency keys and an event log the partner can re-fetch from.

Realtime: polling vs SSE vs WebSockets (and WebRTC)#

When the server must tell the client something without being asked (a new chat message, a price change, a driver's position), there are five main options. Polling, Long Polling, SSE, WebSockets and Webhooks covers the protocols in detail, and Pattern: Pushing Realtime Updates covers the server side: fan-out, pub/sub and connection routing.

Short polling. The client asks every N seconds: GET /leaderboard, GET /submissions/91/status. It's the simplest option and uses ordinary stateless HTTP, so load balancers, caches, auth and autoscaling all work unchanged. The costs are latency (on average half the interval) and wasted requests when nothing has changed. The arithmetic decides whether that matters. 100,000 clients polling every 5 seconds is 20,000 requests per second. If each request is a Redis read or a CDN-cacheable response, a handful of servers handles it. If each poll runs a database query sorting a million rows, it's a disaster.

The LeetCode-style competition leaderboard is the canonical case where polling wins. Scores live in a Redis sorted set (ZADD on each accepted submission; ZRANGE … REV for the top 100). Clients poll every 5 seconds, maybe every 2 seconds in the final minutes. That's near-real-time at a fraction of the complexity of persistent connections. Proposing WebSockets there is a common over-engineering signal. A strong answer names the more complex option and explains why it isn't needed.

Long polling. The client sends a request that the server holds open until there's news or a timeout (often 20–30 seconds), then the client immediately re-requests. Latency is near-instant without a new protocol. The costs: each waiting client holds a server connection, every message costs a full request and response, and with bursty updates the client can miss events between requests unless you pass a cursor ("give me events after ID 1234"). It's a good fallback where SSE and WebSockets are blocked, and the mechanism behind many queue APIs (SQS long polling waits up to 20 seconds).

Server-Sent Events (SSE). The client opens one HTTP request (Accept: text/event-stream), and the server keeps the response open, writing events as lines (data: {...}) over time. The browser's EventSource API parses events and reconnects automatically, sending the last event ID it received in a Last-Event-ID header so the server can replay what was missed. SSE is one-directional (server to client), text-based and plain HTTP, so it passes through most proxies and works with existing auth cookies and headers.

SSE fits notifications, live scores, auction prices, progress updates and streaming LLM tokens. The practical headaches:

  • Proxies, load balancers and idle timeouts close long responses, so expect reconnects and design the replay buffer.
  • Some misbehaving intermediaries buffer the whole stream, which defeats it. Disabling proxy buffering for the route usually fixes this.
  • Browsers limit HTTP/1.1 connections to about six per domain, so several SSE tabs can starve other requests. HTTP/2 multiplexing removes this limit.

WebSockets. The client sends an HTTP request with Upgrade: websocket. The server agrees, and the TCP connection becomes a persistent, bidirectional, message-framed channel. Either side can send at any time with tiny per-message overhead (a few bytes of framing instead of hundreds of bytes of HTTP headers). WebSockets define framing, not meaning, so you design your own message protocol, usually typed JSON messages such as {"type":"send_message","chat_id":…}. WebSockets fit chat, multiplayer games, collaborative editing, live trading terminals, and anything where the client also sends frequent low-latency messages.

The costs are mostly infrastructure:

  • Stateful connections. A server holding 100,000 sockets can't be drained or replaced without disconnecting them. Deploys need connection draining and client reconnect with backoff and jitter.
  • Routing. A message for user U must reach the specific server holding U's socket, which needs a connection registry plus pub/sub (Redis, Kafka or a dedicated broker).
  • Every hop must support it. Proxies, corporate firewalls, load balancers and CDNs all have to carry WebSockets, and idle timeouts need heartbeats (for example, a ping every 30 seconds under a 60-second timeout).
  • Reconnect storms. After an outage, millions of clients reconnecting at once can overload authentication and state loading unless reconnects are jittered.

In interviews, launching into WebSockets without justification is a negative signal. Earn them by pointing at frequent, bidirectional, low-latency traffic.

WebRTC. WebRTC is a browser standard for peer-to-peer audio, video and data channels over UDP. Peers exchange connection details through a signalling server (often over WebSockets). They discover their public addresses with STUN, punching through the network address translation (NAT) devices most clients sit behind, and fall back to a TURN relay when direct connection fails, typically for a meaningful minority of calls behind strict firewalls. WebRTC is the right choice for voice and video calls and conferencing, where sub-200 ms latency and UDP's tolerance of loss matter more than reliability. Group calls usually route through a media server (a Selective Forwarding Unit, SFU) rather than a full peer mesh. Outside media, WebRTC is rarely worth its complexity. Collaborative editors usually need a central server anyway, to persist and order changes, so WebSockets fit better.

OptionDirectionLatencyServer stateInfrastructure frictionPick when
Short pollingClient pullsUp to the intervalNoneNoneUpdates every few seconds are fine; responses cacheable
Long pollingPull, held openNear-instantOne held request per clientLowSSE or WebSockets unavailable; moderate event rates
SSEServer → clientNear-instantOne open response per clientLow to medium (buffering proxies, idle timeouts)Server push only: notifications, prices, token streams
WebSocketsBidirectionalNear-instant, tiny framesOne socket per client, plus routingMedium to high (LBs, deploys, reconnect storms)Frequent two-way messages: chat, games, collaboration
WebRTCPeer to peer, UDPLowestSignalling, STUN and TURN, SFUsHighVoice and video; rarely anything else
WebhooksServer → partner serverSecondsDelivery queue and retriesLowNotifying other backends, not end users

Connection capacity is a frequent follow-up. A tuned server process can hold hundreds of thousands of mostly idle WebSocket or SSE connections. Memory per connection, typically a few KB to tens of KB depending on buffers and language runtime, is usually the limit, not CPU. WhatsApp famously reported holding more than two million TCP connections on a single Erlang server in 2012. For planning, 50,000–100,000 active connections per node is a comfortable assumption, so 10 million concurrent users means roughly 100–200 connection servers, plus headroom for losing a zone.

Caching: where to cache, and Redis vs Memcached#

Caching decisions come in two parts: where in the request path to cache, and which technology holds the cache. Caching Fundamentals and Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind cover the mechanics.

Where. From the client inward:

LayerWhat it cachesTypical toolsFits whenWatch out for
Client (browser or app)Static assets, API responses with Cache-Control, local databasesHTTP cache, service workers, SQLite on mobileData reused by the same userStale data you can't invalidate remotely
CDN / edgeStatic files, media, public API responsesCloudFront, Cloudflare, Fastly, AkamaiSame response for many users; global audiencePersonalised responses must not be cached publicly
API gateway or reverse proxyWhole responses for hot endpointsNGINX, Varnish, gateway cachesSimple, idempotent GETsCache key mistakes leaking data between users
Application in-processHot config, small lookup tablesCaffeine, Guava, in-memory mapsTiny, hot, rarely changing dataN copies to invalidate; memory per instance
Distributed cacheQuery results, sessions, computed objects, countersRedis, Valkey, MemcachedShared across instances; sub-millisecond readsInvalidation, stampedes, hot keys
Database internalPages and query plansPostgreSQL buffer cache, InnoDB buffer poolAlways on; tune memoryNot a substitute for an application cache at scale
Search engine internalFilter results, full responses for repeated queriesElasticsearch filter and request cachesRepeated filters and aggregationsInvalidated on index refresh

A worked case: repeated searches on a ticketing site ("Taylor Swift" plus date filters during an on-sale). You can cache results in Redis under a key built from every parameter that changes the result (keyword, date range, city, page, sort), with a TTL. The TTL might be minutes for availability-sensitive results and hours for static event lists. Invalidation is the hard part, because there's no direct link between "a new event was added" and "which cached queries would now include it". Practical answers combine short TTLs, tag-based invalidation (tag each entry with the entities it depends on, and purge by tag on change), and accepting a bounded staleness window.

The search engine's own caches help too: Elasticsearch caches filter results at the shard level, plus a request cache for full responses, especially aggregations. If results are not personalised, a CDN can cache the search responses near users. Personalised results, such as "events near you, from artists you follow", can't be cached publicly.

Which: Redis vs Memcached. Both are in-memory key-value stores with sub-millisecond latency. The differences decide the choice:

MemcachedRedis (and the Valkey fork)
Data modelOpaque strings (byte blobs) up to 1 MB by defaultStrings, hashes, lists, sets, sorted sets, streams, bitmaps, HyperLogLog, geospatial indexes
ThreadingMultithreaded; scales across cores in one processCommand execution essentially single-threaded per process (I/O threads since 6.0); scale by running more shards
Memory managementSlab allocator; predictable, little fragmentation; LRU per slab classGeneral allocator (jemalloc); several eviction policies (LRU, LFU, TTL-based)
PersistenceNoneOptional: RDB snapshots and an append-only file
Replication and HANone built in; the client hashes keys across serversReplicas, Sentinel failover, Redis Cluster with 16,384 hash slots
Atomic operationsGet, set, CAS, incrementRich atomic commands, transactions, Lua scripts and functions
Pub/sub and streamsNoYes
Best fitA pure, large, simple cache where multithreaded throughput per node and simplicity matterAlmost everything else: caches plus counters, rate limits, leaderboards, locks, sessions, queues, geo, pub/sub

The usual answer is Redis by default. Its data structures turn many problems that would otherwise need a database round trip into one atomic command: INCR for counters, ZADD/ZRANGE for leaderboards, SET NX PX for short locks and holds, GEOSEARCH for nearby drivers. And having one technology for cache and ephemeral state reduces operational surface. Memcached remains a good choice for very large, simple object caches. Facebook's Scaling Memcache at Facebook (Nishtala et al., NSDI 2013) describes running it as a cache tier for billions of requests per second, with leases against stampedes, regional pools and cross-region invalidation through MySQL replication streams.

One licensing note. In 2024 Redis moved away from its permissive BSD licence, and the Linux Foundation started Valkey as a BSD-licensed fork; several cloud providers now offer Valkey-based managed services. Redis later added an AGPL licence option. For design purposes they behave the same; organisations choose between them on licensing and vendor support.

Picking Redis also means designing around its limits:

  • Memory bounds everything. The dataset (plus overhead and replication buffers) must fit in RAM. Set maxmemory and an eviction policy deliberately. A cache that hits its limit should evict, not reject writes, but a queue or lock store that evicts loses data. This is exactly how Slack's Redis job queue failed (see Real-World Examples).
  • Single-threaded execution means one slow command (KEYS *, a huge ZRANGE, a big Lua script) blocks everyone on that shard.
  • Hot keys concentrate on one shard. Replicate hot reads, split the key, or add a small in-process cache in front.
  • Persistence isn't durability for a system of record. Asynchronous replication and fsync-per-second AOF can lose recent writes on failover.

Rough planning numbers: one Redis shard handles on the order of 100,000 simple operations per second at sub-millisecond latency, more with pipelining. A cache hit costs about 0.2–1 ms in the same zone, against 1–10 ms for an indexed database query and tens of milliseconds or more for a cross-region call. Distributed Caching with Redis and Memcached and Redis in Practice go deeper.

Messaging: queue vs stream#

"Put a queue in between" is one of the most common moves in system design, but there are two different kinds of system behind the word, and choosing the wrong kind causes real pain. Asynchronous Processing and Message Queues and Pub/Sub and Event Streaming cover the internals.

A message queue (RabbitMQ, SQS, ActiveMQ, a Redis list) is a to-do list of work items. Producers add messages; consumers take them, process them and acknowledge each one, after which it is deleted. An unacknowledged message is redelivered after a timeout: SQS's visibility timeout defaults to 30 seconds, and RabbitMQ redelivers when the consumer's channel closes. Many workers share one queue, and each message goes to one of them (competing consumers). The broker tracks per-message state: in flight, acknowledged, retried or dead-lettered. That makes the queue ideal for jobs: send this email, resize this image, charge this card. Messages vanish once handled, so there's no replay. Ordering is usually best-effort, except in FIFO variants.

An event stream or log (Kafka, Kinesis, Pulsar, Redpanda, Redis Streams) is an append-only, ordered, retained record of facts. Producers append events to partitions. Consumers don't delete anything: each consumer group tracks its own offset (position) per partition and reads forward. Events stay for a retention period (days, weeks or forever, via tiered storage), so many independent consumer groups can each read the full stream, new consumers can start from the beginning, and a buggy consumer can rewind and replay. Ordering is guaranteed within a partition, so events for one key (one user, one order) are processed in order. The broker tracks only an offset per partition, not per-message state, which is a big part of why logs scale to millions of events per second. The cost is that per-message acknowledgment, per-message retry and delay, and dead-lettering must be built on top, and parallelism is capped by the partition count.

NeedQueueStream / log
Distribute jobs to a pool of workersNatural fitPossible; parallelism capped by partitions
Per-message ack, retry, delay, dead-letterBuilt inBuild it yourself (retry topics, DLQ topics)
Several independent consumers of the same eventsNeeds fan-out (exchanges, SNS to many queues)Natural: one consumer group each
Replay history after a bug, or bootstrap a new consumerNo (deleted after ack)Yes, within retention
Strict ordering per keyFIFO variants, limited throughputPer partition, at high throughput
ThroughputThousands to tens of thousands of messages per second per queue; SQS standard scales very highHundreds of thousands to millions of events per second per cluster
Backlog behaviourGrows in broker storage; per-message bookkeeping grows with itJust a longer log on disk, bounded by retention
Typical usesBackground jobs, task distribution, request bufferingEvent-driven architecture, CDC, analytics pipelines, activity streams, audit logs

Rule of thumb: if the message is a command ("do this"), use a queue; if it is a fact ("this happened") that several parties care about, use a log. Many systems use both. A log carries domain events, and a consumer turns some of them into jobs on a queue.

Kafka vs RabbitMQ vs SQS (and relatives)#

Apache KafkaRabbitMQAmazon SQS
ModelPartitioned, replicated log with consumer offsetsBroker with exchanges routing to queues (AMQP); also streams since 3.9Fully managed queue: standard (at-least-once, best-effort order) or FIFO
RoutingBy topic and partition keyRich: direct, topic (wildcards), fanout and headers exchangesNone (use SNS or EventBridge for fan-out)
Retention and replayConfigurable retention, replay by offset, tiered storageMessages deleted on ack (streams retain)Retained up to 14 days (default 4) until deleted; no replay after ack
OrderingPer partitionPer queue, with a single consumerFIFO queues per message group
ThroughputVery high: hundreds of MB/s per broker with batchingTens of thousands of messages/s per node, typicalStandard: nearly unlimited; FIFO: 300 messages/s per API action, 3,000 with batching, more in high-throughput mode
DeliveryAt-least-once; exactly-once within Kafka using idempotent producers and transactionsAt-least-once with publisher confirms and acksAt-least-once (standard); exactly-once processing within the deduplication window (FIFO)
OperationsSignificant if self-run (brokers, KRaft controllers, partitions, rebalancing); managed: Confluent Cloud, MSKModerate; quorum queues for HA; managed: Amazon MQ, CloudAMQPNone: pay per request
Pick whenEvent streams with many consumers, replay, CDC, analytics, very high throughputComplex routing, per-message semantics, priorities, request/reply, moderate throughputOn AWS and you want a job queue with zero operations

Relatives worth knowing, each with its fit:

  • Google Cloud Pub/Sub: managed pub/sub with per-message acks and replay-by-seek; GCP's default for both queue-like and stream-like use.
  • Amazon Kinesis Data Streams: a managed log with shards, AWS's managed Kafka-like option (MSK is managed Kafka itself).
  • Azure Service Bus (queues and topics) and Event Hubs (a log with a Kafka-compatible endpoint).
  • Apache Pulsar: a log that separates serving brokers from storage (Apache BookKeeper), with multi-tenancy, geo-replication and both queue-style and stream-style subscriptions. It fits large multi-tenant platforms.
  • Redpanda: Kafka-API-compatible, written in C++ without the JVM or ZooKeeper, aimed at lower tail latency and simpler operations.
  • Redis lists and Streams: very fast and simple, but bounded by memory. Fine for small, latency-sensitive queues, risky as the only home for a large backlog.
  • NATS / JetStream: lightweight messaging with optional persistence, popular for edge and IoT.
  • Cloud task services (Cloud Tasks, SQS delay queues) and workflow engines (Temporal, Step Functions) for scheduled and multi-step work. See Temporal and Workflow Engines.

How to decide in practice:

  1. Is it a job or an event? Jobs → queue; events with several consumers or replay → log.
  2. Throughput and retention. Below about 1,000 messages per second with no replay, a queue is simplest. Tens of thousands per second, or any need to replay, points to a log.
  3. Routing complexity. Content-based routing, priorities and request/reply point to RabbitMQ.
  4. Operations budget. On AWS with a small team, SQS (plus SNS for fan-out) or MSK Serverless avoids running brokers. Self-hosting Kafka is worth it only with a platform team or at a scale where managed pricing hurts.
  5. Ecosystem. Kafka Connect, Debezium, Flink and ksqlDB make Kafka the hub for CDC and stream processing. If those are coming, start there.

Apache Kafka in Practice and Delivery Guarantees: At-Most, At-Least and Exactly-Once go deeper. Whatever you choose, consumers must be idempotent, because every option above can deliver a message more than once.

Compute: VMs, containers or serverless#

Where code runs is the fourth family. Containers and Kubernetes and Serverless and Functions-as-a-Service cover each model; here is the choice.

  • Virtual machines (EC2, Compute Engine, Azure VMs): you get an OS and manage everything above it. Maximum control: kernel settings, GPUs, local NVMe disks, licensed software, very long-running processes. Most manual work, unless wrapped in autoscaling groups and images.
  • Containers (Docker images run on Kubernetes, ECS, Cloud Run or Azure Container Apps): you package the app and its dependencies into an image. An orchestrator schedules images onto machines, restarts them, scales them and routes traffic. Containers start in seconds, pack densely, behave the same on a laptop and in production, and suit long-running services, steady traffic, persistent connections (WebSockets) and background workers. The cost is the platform: running Kubernetes well is a real job, which is why managed services (EKS, GKE, AKS) and "serverless containers" (Cloud Run, Fargate) exist.
  • Serverless functions (AWS Lambda, Google Cloud Functions, Azure Functions, Cloudflare Workers at the edge): you upload a function, and the platform runs it on demand, scales from zero to thousands of concurrent instances, and bills per request and per millisecond of execution. Zero idle cost and zero servers to manage. The constraints:
    • Execution limits, for example Lambda's 15-minute maximum.
    • Cold starts. The first invocation after idle must create a sandbox and initialise the runtime: from under 100 ms for lightweight runtimes to a second or more for heavy JVM apps, mitigated by provisioned concurrency or snapshotting.
    • Statelessness. No in-memory state survives between invocations reliably.
    • Concurrency quotas, for example a default regional limit of 1,000 concurrent Lambda executions per account, raisable.
    • Cost at sustained load. Steady traffic is usually cheaper on containers.

A worked cost comparison. Approximate public list prices for x86 Lambda in a major US region are about $0.0000167 per GB-second plus $0.20 per million requests. Always check current pricing; the shape of the curve is the point here.

  • Spiky workload: an image-thumbnail function at 512 MB running 200 ms, invoked 2 million times a month. Compute is 2M × 0.2 s × 0.5 GB = 200,000 GB-seconds ≈ $3.30, plus $0.40 for requests: about $4 a month, with no idle servers. Even the smallest always-on container pair (for availability) costs more.
  • Steady workload: an API at a constant 300 requests/s, 100 ms each, 512 MB. That's 300 × 0.1 × 0.5 = 15 GB-seconds per second, or about 39 million GB-seconds a month ≈ $650, plus about 778 million requests ≈ $155: roughly $800 a month. On containers, 300 requests/s at 100 ms is 30 concurrently busy requests. A few small instances, with headroom and redundancy, typically cost a fraction of that.

Functions win for spiky, low-to-moderate, event-triggered work: webhooks, file-upload triggers, scheduled jobs, glue between managed services, and traffic that sits near zero most of the day. Containers win for steady, high-throughput services and anything holding long-lived connections. Amazon Prime Video's video-quality monitoring team wrote in 2023 that moving one high-throughput pipeline from a distributed design of Step Functions and Lambda to a single process on ECS reduced its infrastructure cost by about 90%. The lesson isn't "serverless is bad". It's that per-invocation pricing and state passing between functions get expensive for continuous, data-heavy flows.

Build vs buy#

For every component, there are usually four options: build it, self-host open source, use a managed cloud service, or buy a SaaS product. Authentication, search, payments, email delivery, feature flags, observability and workflow orchestration all have strong commercial and managed offerings.

Ask these questions in order:

  1. Is this a differentiator? If customers choose you because of it (Google's ranking, Uber's dispatch, a trading firm's matching engine), building is justified. If it is undifferentiated plumbing (login, email sending, metrics storage), buying is usually right. Spend engineers on what makes the product unique.
  2. What is the total cost of building? Include the first version (often 2–5× the estimate) and the permanent maintenance: security patches, on-call, upgrades, documentation, and the engineers who could have built product features instead. Roughly, one engineer-year fully loaded costs as much as a large SaaS contract.
  3. What is the total cost of buying? Subscription or usage fees at your projected scale (per-seat and per-event pricing can explode), integration effort, vendor reliability (their outage is your outage), data residency and compliance, and exit cost.
  4. How good are the existing options? Mature, well-understood categories (auth, payments, CDNs) are hard to beat. Immature categories may force you to build.
  5. What is the risk profile? Security- and compliance-heavy components (cryptography, payment card handling, identity) are where in-house mistakes are most expensive. Buying from specialists also reduces audit scope; tokenising cards with a payment provider keeps raw card data out of your systems.
OptionProsConsPick when
BuildExactly fits; no vendor fees; can become a differentiatorSlow; maintenance forever; needs expertiseCore differentiator, or no adequate option exists
Self-host open sourceNo licence fees; control; portabilityYou operate it: upgrades, scaling, on-callStrong platform team, scale where managed pricing hurts, portability needs
Managed cloud serviceLittle operational work; integrated with the cloudLock-in; cost at scale; less controlDefault for infrastructure on your cloud
SaaS productFastest; expertise included; continuous improvementFees at scale; data leaves your boundary; vendor riskUndifferentiated capabilities: auth, email, payments, monitoring

A healthy default: buy or rent commodity capabilities, build the core. Revisit as you grow. A SaaS bill that was cheap at 10,000 users can justify an in-house replacement at 10 million, and the reverse happens when a home-grown system's maintainers leave.

A "boring technology" default stack#

Combining the defaults above gives a stack that serves the vast majority of products from launch to tens of millions of users. Every component is mature, widely understood and available as a managed service on every major cloud. Treat it as the starting point that you deviate from for a stated reason, not as a rule.

LayerDefaultCommon deviations, with the trigger
EdgeManaged DNS plus a CDN (CloudFront, Cloudflare, Fastly)Edge functions when personalisation must happen near users
IngressCloud load balancer; API gateway for auth, rate limits and routingEnvoy or a service mesh when there are dozens of services with complex traffic policies
External APIREST + JSON over HTTPS, OpenAPI contractGraphQL or a BFF for many diverse clients; gRPC-Web for internal tools
Internal callsREST at first; gRPC on hot pathsAsync events instead of calls for cross-domain side effects
RealtimePolling, then SSEWebSockets for bidirectional chat or games; WebRTC for media
ComputeContainers on a managed platform (ECS, Cloud Run, managed Kubernetes)Functions for spiky event glue; VMs for GPUs or special hardware
System of recordPostgreSQL (managed: RDS, Aurora, Cloud SQL, AlloyDB)DynamoDB or Cassandra for massive key-based writes; distributed SQL beyond one primary
CacheRedis or Valkey (managed)Memcached for huge simple caches; in-process caches for tiny hot data
Async jobsSQS, Cloud Tasks or RabbitMQTemporal or Step Functions when jobs become multi-step workflows
EventsKafka (managed) or the cloud's pub/subKinesis or Pulsar for platform reasons
FilesS3-compatible object storage with presigned URLsA specialised media pipeline for video
SearchPostgreSQL full-text at small scale; then Elasticsearch or OpenSearch via CDCVector search alongside for semantic retrieval
AnalyticsWarehouse (BigQuery, Snowflake, Redshift) fed by CDC or eventsClickHouse, Druid or Pinot for user-facing real-time analytics
ObservabilityOpenTelemetry; Prometheus and Grafana or a SaaS vendor; structured logsDedicated tracing backends at large scale
DeliveryGit, CI (GitHub Actions or GitLab CI), Terraform, blue-green or canary deploysGitOps (Argo CD, Flux) on Kubernetes

Notice what's missing: no service mesh, no graph database, no event sourcing, no multi-region active-active, no custom consensus. These are innovation-token spends, justified only by a specific requirement. A useful interview move is to draw this baseline quickly, then spend time on the two or three places where the problem forces a deviation. The deviations are where the interesting design lives.

Key technologies cheat sheet#

A one-line-each reference for the technologies that appear most often in designs, with the property that makes each one fit and rough numbers for sizing. The numbers are planning figures for a single, reasonably sized node or default configuration. Real results vary several-fold with hardware, payload and tuning; measure before you commit.

TechnologyWhat it isReach for it whenPlanning numbers
PostgreSQLRelational database with ACID transactions and rich SQLDefault system of recordThousands to tens of thousands of simple writes/s and far more indexed reads/s per primary; comfortable into several TB
MySQL with VitessRelational database plus a sharding layerMySQL shop outgrowing one primaryScales horizontally across many shards
Redis / ValkeyIn-memory data-structure serverCache, counters, leaderboards, rate limits, short locks, presence~100k+ ops/s per shard; sub-ms; data must fit in RAM
MemcachedMultithreaded in-memory cacheHuge, simple object cachesVery high ops/s per node; no persistence
KafkaPartitioned, replicated, retained logEvent streams, CDC, analytics feeds, fan-out with replayHundreds of MB/s per broker; ordering per partition; days of retention
RabbitMQAMQP broker with routing exchangesJob queues with routing, priorities, request/replyTens of thousands of messages/s per node
SQS / Cloud Tasks / Service BusManaged queuesJob queues without operationsStandard SQS scales very high; visibility timeout default 30 s
Elasticsearch / OpenSearchDistributed inverted indexFull-text search, facets, log searchIndex refresh ~1 s (near-real-time); shards of tens of GB
Cassandra / ScyllaDBWide-column LSM store, leaderless replicationMassive append-heavy writes, multi-regionTens of thousands of writes/s per node; linear scale-out
DynamoDBManaged key-value and document storeKnown key access at large, spiky scale on AWSSingle-digit-ms reads and writes; per-partition limits around 3,000 reads and 1,000 writes per second
S3 / GCS / Azure BlobObject storageFiles, media, backups, data lakesEffectively unlimited capacity; tens of ms first-byte latency
CDNEdge caches near usersStatic assets, media, cacheable responsesEdge hits in tens of ms; offloads most static traffic
FlinkStateful stream processorWindowed aggregation, joins, exactly-once pipelinesLarge keyed state with checkpoints
ZooKeeper / etcdConsensus-backed coordination storesLeader election, config, service discovery, locksThousands of writes/s; small data only
TemporalDurable workflow engineMulti-step processes with retries, timers and compensationWorkflows from seconds to months
Vector index (pgvector, dedicated DBs)Approximate nearest-neighbour searchSemantic search, retrieval for LLMs, recommendationspgvector into the tens of millions of vectors; dedicated at 100M+
Time-series DB (Prometheus, TimescaleDB)Compressed time-ordered storageMetrics and IoT readings~1–2 bytes per sample with Gorilla-style compression

Latency anchors to keep in mind: same-zone network round trip under 1 ms; cross-zone in a region 1–2 ms; cross-continent 50–150 ms; Redis hit ~0.5 ms; indexed database read 1–10 ms; SSD random read ~0.1 ms. For the full set see Numbers Every Engineer Should Know. The modern-hardware lesson behind those numbers: a single large machine today has hundreds of vCPUs and terabytes of RAM, so many workloads that once required distributed systems now fit on one well-tuned node. Shard and distribute when the numbers demand it, not by reflex.

When to Use It#

Use this guide every time a box goes on the diagram, and especially at these moments:

  • Drawing the high-level design. Each arrow is a communication choice and each box a compute and storage choice. Name them with a one-line reason.
  • When a requirement implies a property. "Users see updates instantly" means push, so choose a transport. "Survive worker crashes" means acknowledged delivery, so use a queue. "Several teams consume the same events" means a log. "Traffic is near zero at night and huge at lunch" points to serverless or aggressive autoscaling.
  • When an existing choice starts to hurt. A Redis queue near its memory limit, polling load dominating the API fleet, a REST endpoint called 40 times per page, a function bill exceeding the equivalent containers.
  • When evaluating a vendor or a proposal to adopt a new technology. Run it through the four filters (fit, team, operations, maturity) before the proof of concept.

Pick something else instead when:

  • The organisation has a paved road. If the platform team supports Kafka and PostgreSQL, a design using Pulsar and CockroachDB needs a strong reason. Use the supported tools and note any fit gap.
  • The decision is cheap to reverse. Choosing a JSON library or an internal HTTP framework doesn't need this process.
  • You're prototyping. For a throwaway spike, use whatever you're fastest with, and run the process before the prototype becomes production.

When NOT to Use It#

  • Don't evaluate technologies before requirements. Comparing Kafka with Pulsar before knowing the message rate, retention and consumer count is wasted effort.
  • Don't optimise components that aren't bottlenecks. Switching REST to gRPC to save 2 ms on a call dominated by a 200 ms database query achieves nothing. Profile first.
  • Don't add a technology to show knowledge. In interviews especially, every extra component is something you must defend. A design with five well-justified components beats one with twelve name-dropped ones.
  • Don't treat the defaults as dogma. The boring stack is a baseline. When a requirement clearly breaks it (sub-50 ms global writes, millions of events per second, peer-to-peer media), deviate decisively.

How to Implement It#

A repeatable procedure for technology choices on a real project:

  1. List the components the design needs, as categories: "external API", "push channel", "job queue", "event bus", "cache", "compute for workers".
  2. Write the driving properties for each, with numbers: request rate, payload size, latency target, delivery guarantee, ordering, retention, fan-out, burstiness, connection count.
  3. Shortlist candidates using the tables above. Always include "what we already run".
  4. Score against the four filters. Disqualify on fit first; then compare team familiarity, operations and maturity.
  5. Spike the riskiest property. Measure WebSocket connections per node, Kafka throughput with your message size and acks setting, or Lambda cold start with your runtime and dependencies.
  6. Estimate cost at today's and 10× load, including data transfer, which is often the surprise.
  7. Record the decision in an ADR with the revisit triggers (see The Design Process: From Problem to Architecture), and add it to a team technology radar. ThoughtWorks popularised this format, with rings Adopt, Trial, Assess and Hold, so later teams reuse proven choices instead of re-evaluating.
  8. Plan operations: dashboards for the component's key signals (consumer lag, cache hit ratio, connection counts, cold-start rate), alerts, runbooks and an upgrade path.

A lightweight decision record captures steps 2–7 and makes the reasoning reviewable:

# tech-decision: async job transport for notifications service
component: job queue for push/email/SMS sends
properties:
  peak_rate: 4000 msgs/s        # campaign blasts; 300/s typical
  payload: 2 KB                 # template id + recipient + vars
  delivery: at-least-once       # sends are idempotent by notification_id
  ordering: none required
  retention_replay: not needed  # analytics reads events from Kafka already
  per_message_retry: required   # provider 5xx -> retry with backoff, then DLQ
  delay: required               # scheduled sends up to 7 days
candidates:
  - name: SQS standard + DLQ
    fit: strong                 # ack, visibility timeout, DLQ, delay up to 15 min
    gaps: "delays over 15 min need a scheduler table"
    ops: none (managed)
  - name: Kafka topic + retry topics
    fit: partial                # per-message retry/delay must be built
    ops: shared cluster exists
  - name: RabbitMQ
    fit: strong
    ops: "new system for this team"
decision: SQS standard + DLQ; scheduler table in PostgreSQL for long delays
revisit_if:
  - "peak exceeds 50k msgs/s or we leave AWS"
  - "ordering per user becomes a requirement (then SQS FIFO or Kafka)"
cost_estimate_monthly: "~$40 at typical load, ~$400 at 10x"
TechnologyFits when
REST + OpenAPIPublic and partner APIs, simple CRUD, the default
gRPCInternal, high-volume, polyglot service calls and service-to-service streaming
GraphQL (Apollo, GraphQL Yoga, Hasura)Many client types with different data needs; BFF layers
SSEOne-way server push to browsers: notifications, prices, token streams
WebSockets (Socket.IO, uWebSockets, managed: API Gateway WebSockets, Pusher, Ably)Bidirectional, frequent, low-latency messaging
WebRTC (with SFUs such as mediasoup, Janus, LiveKit)Voice and video between users
Redis / ValkeyShared cache plus ephemeral data structures
MemcachedVery large, simple, multithreaded object caching
SQS, Cloud Tasks, Azure Queue StorageManaged job queues with zero operations
RabbitMQRouting-heavy job queues, priorities, request/reply
Kafka, Kinesis, Event Hubs, Pulsar, RedpandaEvent streams with fan-out, ordering per key and replay
Kubernetes, ECS, Cloud RunLong-running services and workers
Lambda, Cloud Functions, Azure Functions, WorkersSpiky, event-triggered, short-lived work
Temporal, Step FunctionsDurable multi-step workflows

Trade-offs#

OptionProsConsPick when
Boring, proven defaultsKnown failure modes; easy hiring; rich toolingMay not be optimal for unusual requirementsAlmost always, as the starting point
Specialised technology for a hard requirementSolves the requirement well; possible competitive edgeSpends an innovation token; new operational skills; smaller communityA requirement the defaults clearly can't meet
Managed servicesMinimal operations; fast to adopt; built-in HALock-in; cost grows with usage; less controlSmall and medium teams; commodity infrastructure
Self-hosted open sourceControl; portability; cheaper at large scaleOperational burden; needs expertise and on-callLarge scale with a platform team, or regulatory or portability needs
One technology for many roles (Redis for cache, queue and locks)Fewer systems to runRoles compete for the same resource, as in Slack's memory-bound queueSmall scale, with roles that fail gracefully
Purpose-built technology per roleEach role isolated and well-servedMore systems, more integrationWhen roles have different durability or scale needs

Common Pitfalls#

  • WebSockets by reflex. Persistent connections where polling every few seconds or SSE would do.
  • Using Kafka as a job queue without building job semantics: no per-message retry or delay, a poison message blocking a partition, parallelism capped by partition count.
  • Using a queue where a log was needed. Discovering later that a second consumer, or a replay after a bug, is impossible because messages were deleted.
  • Memory-bound backlogs. Large or unbounded backlogs held in Redis or another in-memory store with no durable buffer.
  • Non-idempotent consumers on at-least-once delivery, which is every mainstream broker.
  • GraphQL without guardrails: N+1 resolvers, unbounded query depth, and no caching plan.
  • gRPC behind an L4 load balancer, where one long-lived HTTP/2 connection pins all traffic to one backend.
  • Serverless for steady high load, paying many times the container cost, or chaining functions that pass large payloads through storage.
  • Building commodity infrastructure (auth, email delivery, feature flags) in-house without a reason, and maintaining it forever.
  • Ignoring data transfer costs: cross-zone replication traffic, NAT gateway charges and internet egress often exceed compute.
  • Too many technologies for the team's size: five datastores, three brokers and two orchestrators run by a team of eight.

Real-World Examples#

Slack: Kafka in front of a Redis job queue. Slack's 2017 engineering write-up is the best public case study of a queue-versus-log decision. Slack's asynchronous job queue handles work too slow for a web request: posting messages, push notifications, link unfurls, reminders, billing calculations. On busy days it processed more than 1.4 billion jobs, peaking around 33,000 per second.

The original queue lived entirely in Redis. Producers hashed each job to a Redis cluster, which ran a light deduplication check; workers moved jobs from a pending list to an in-flight list while running them, and failed jobs retried before landing in a permanently-failed list. The same RAM held the burst buffer (the backlog) and the dispatch bookkeeping (dedup, in-flight, retries).

When a database slowdown made jobs run slowly, the backlog grew until Redis hit its memory limit. Enqueues then failed, breaking every feature that depended on the queue. Worse, dequeuing also needed a little free memory, to move a job onto the in-flight list, so the queue stayed stuck even after the database recovered, and needed extensive manual intervention. The post-mortem found more structural problems:

  • every client connected to every Redis instance;
  • adding workers added polling load on the already overloaded Redis;
  • dequeue cost grew with queue length, a second feedback loop at exactly the wrong moment;
  • the queue's semantics were never clearly specified, so engineers were wary of changing them.

The options Slack weighed are instructive:

  • Rebuild on Kafka alone. A durable, disk-backed log can't run out of RAM. But Kafka tracks offsets, not per-job state, so acknowledgment, retries, dedup and in-flight tracking would have had to be rebuilt, and years of application code depended on the existing semantics.
  • Switch to RabbitMQ, SQS or beanstalkd. These persist to disk, but each brings its own delivery semantics, so this meant the same rewrite against a different API.
  • Turn on Redis persistence. This wouldn't help: the data must still fit in RAM. The outage was a capacity problem, not a durability problem.

Slack chose the minimum viable change. The web app enqueues into Kafka through a new stateless Go service (Kafkagate), which writes synchronously and waits for the partition leader's acknowledgment only. That's lower latency, with a small risk of loss if a broker dies before replicating, a trade-off judged acceptable for most jobs. A second Go service (JQRelay), one active instance per topic coordinated by Consul locks, drains Kafka into the existing Redis clusters at an operator-controlled rate, committing each Kafka offset only after the Redis write succeeds. Redis kept providing the short dispatch queue and the semantics the application knew. During a buildup, the backlog piles up on disk in Kafka while operators throttle the flow into Redis to match worker capacity.

The cluster ran 16 brokers, 32 partitions per topic, replication factor 3 and two days of retention. The rollout used double writes and a "shadow" relay that read and discarded, per-hop job counts, and per-partition heartbeat canaries, then moved job types over one at a time. One surprise: Go and PHP escape different characters in JSON by default, so re-encoded jobs differed byte for byte.

The lesson generalises: keep the backlog in something that can't run out of memory, and let the fast in-memory layer hold only what's in flight. Today SQS, Kafka consumer groups or a durable-execution engine like Temporal would absorb much of that separation out of the box.

Facebook: Memcached as a cache tier. Scaling Memcache at Facebook (Nishtala et al., NSDI 2013) describes using Memcached, a deliberately simple multithreaded cache, as a demand-filled look-aside cache in front of MySQL, at billions of requests per second. The engineering went into the layer around it: leases to prevent stampedes and stale sets, regional pools, and invalidations driven from MySQL's replication stream. The choice of a simple cache plus well-designed protocols around it, over a feature-rich store, is a model of using a boring component well.

LinkedIn: building Kafka. Kafka came out of LinkedIn's need to move activity and operational data to many consumers (Hadoop, search, monitoring) at high volume. Existing message queues focused on per-message delivery guarantees that LinkedIn didn't need, and lacked the throughput and retention it did. Kafka: a Distributed Messaging System for Log Processing (Kreps, Narkhede and Rao, NetDB 2011) explains the log-centric design: sequential disk I/O, batching, consumer-tracked offsets and retention-based replay. It's a case where a real, specific requirement justified building new infrastructure, which then became the industry's boring default.

GitHub and Shopify: GraphQL for diverse clients. GitHub launched its GraphQL API (v4) in 2016 alongside the REST API, and Shopify's Admin API is GraphQL-first. Both serve thousands of third-party developers with very different data needs, the situation where client-shaped queries beat fixed endpoints. Both meter usage with query-cost calculations rather than simple request counts, the guardrail GraphQL needs.

Amazon Prime Video: from functions to a container. The 2023 Prime Video engineering post described a video-quality monitoring pipeline built from Step Functions and Lambda that hit scaling limits and high costs, from per-transition charges and from passing video frames between components through S3. Re-architected as a single process on ECS, it cost about 90% less to run. Serverless was a good fit for getting started, and a poor fit for a continuous, data-heavy stream.

WhatsApp: connections per server. WhatsApp's 2012 engineering blog reported more than two million concurrent TCP connections on a single FreeBSD server running Erlang. Persistent-connection systems are memory- and tuning-bound rather than CPU-bound, and the right runtime plus careful OS tuning can make the connection tier very compact.

Case studies that use this pattern#

In the Interview#

Phrases that work well:

  • "Clients poll every 5 seconds against Redis. That's 20,000 requests per second at 100,000 users, which a few servers handle, so I don't need persistent connections here."
  • "Bids must reach watchers within a second and only flow server to client, so SSE. If we add in-auction chat, I'd move to WebSockets."
  • "Payment events go to Kafka, because ledger, fraud, notifications and analytics all consume them independently, and we want replay. The email sends themselves go on SQS, because each one needs its own retries and a dead-letter queue."
  • "Thumbnail generation runs in Lambda, triggered by S3 upload events. It's spiky and stateless. The API runs on containers because its load is steady."

Common follow-ups:

  • "Why not WebSockets?" Explain the latency need and the direction of traffic; quantify the polling load; mention connection-state costs.
  • "How do WebSocket servers find the right connection?" A connection registry (user → server) in Redis, plus pub/sub or direct routing; reconnect with jittered backoff.
  • "What if the queue backs up?" Durable backlog (disk, not RAM), autoscale consumers on lag, load-shed or prioritise, and use a DLQ for poison messages. Slack's story is a good reference.
  • "Why Kafka over SQS here?" Fan-out to several consumers, replay, ordering per key and throughput. Or the reverse: per-message retry and delay with zero operations.
  • "gRPC or REST between services?" REST unless call volume or latency makes serialisation matter; gRPC needs L7 or client-side load balancing.
  • "Redis or Memcached?" Redis for data structures and replication; Memcached for huge, simple caches using all cores per node.
  • "Serverless or containers?" Traffic shape and duration: spiky and short favours functions, steady and long-running favours containers. Mention cold starts and the cost crossover.
  • "Would you build or buy authentication?" Buy, or use the cloud's identity service, unless identity is the product; explain the risk and maintenance cost.
Deep Dive: Protocol internals that drive API and transport choicesShow

HTTP versions and head-of-line blocking. HTTP/1.1 handles one request at a time per connection, so a slow response blocks the ones queued behind it (head-of-line blocking). Browsers compensate by opening about six connections per origin. HTTP/2 (RFC 7540, 2015; revised as RFC 9113, 2022) multiplexes many streams over one TCP connection, with binary framing and header compression (HPACK). One connection can carry hundreds of concurrent requests, which is what gRPC builds on. But HTTP/2 still runs over TCP, and TCP delivers bytes in order: one lost packet stalls every stream on the connection until it's retransmitted. On lossy mobile networks this transport-level head-of-line blocking can make HTTP/2 slower than several HTTP/1.1 connections. HTTP/3 runs over QUIC (RFC 9000, 2021), which runs over UDP and implements reliability per stream, so a lost packet stalls only its own stream. QUIC also combines the transport and TLS 1.3 handshakes (one round trip, or zero for resumed connections), and supports connection migration when a phone switches from Wi-Fi to cellular. HTTP, HTTP/2, HTTP/3 and HTTPS covers the details.

The protobuf wire format. Each field is encoded as a key, (field_number << 3) | wire_type, followed by the value. Integers use varints: 7 bits per byte, with the high bit meaning "more bytes follow". So 1 costs one byte, 300 costs two, and values below about 2 million cost at most three. Strings and nested messages are length-prefixed. Negative numbers in plain int32 fields cost 10 bytes; sint32 uses ZigZag encoding to keep small negatives small. Field names never appear on the wire, which is where most of the size saving over JSON comes from. Typical payloads shrink 3–10× and parse several times faster.

The schema-evolution rules matter more than the size:

  • Never reuse or renumber a field number. Old readers would misinterpret the bytes. Mark removed fields reserved.
  • Adding fields is safe. Old readers skip unknown fields, and new readers see defaults for missing ones.
  • Changing a field's type is mostly unsafe. A few changes are compatible, such as int32 to int64.
  • proto3 has no "required". Required fields made evolution brittle, so validation moves into application code.

Avro (schema shipped or registered separately, used heavily with Kafka and a schema registry) and Thrift (from Facebook) follow similar ideas. For event streams, a schema registry enforcing backward or forward compatibility is what keeps hundreds of producers and consumers from breaking each other.

Why gRPC breaks simple load balancing. gRPC clients open one long-lived HTTP/2 connection and multiplex every call over it. A layer-4 load balancer balances connections, not requests, so each client's traffic is pinned to whichever backend it connected to first. After a scale-up, new backends receive almost nothing; after a deploy, load is badly skewed. There are three standard fixes:

  1. An L7 proxy that understands HTTP/2 and balances per request (Envoy, NGINX, cloud L7 load balancers, a service-mesh sidecar).
  2. Client-side load balancing. The client resolves all backend addresses (through DNS, xDS or a registry) and spreads calls across connections itself.
  3. Bounding connection age (MAX_CONNECTION_AGE on the server), so clients periodically reconnect and redistribute.

Kubernetes users hit this constantly, because a ClusterIP Service is L4. A headless Service plus client-side balancing, or a mesh, is the usual answer.

Deadlines, not timeouts. gRPC propagates an absolute deadline across hops. If the edge allows 300 ms and 120 ms are spent before calling service B, B receives a 180 ms budget and can abandon work the caller will no longer wait for. With independent per-hop timeouts, deep call chains keep doing work for requests that have already failed upstream, wasting capacity exactly when the system is overloaded. Resilience Patterns: Timeouts, Retries and Circuit Breakers covers budgets and retries.

GraphQL execution costs, with numbers. Take a query for 50 orders, each with its customer and its line items. A naive resolver tree runs 1 query for the orders, 50 for customers and 50 for items: 101 database round trips. At 1 ms each that's about 100 ms of serial latency before any processing. A DataLoader-style batcher collects all keys requested in one tick of the event loop and issues WHERE id IN (...) queries, reducing this to 3 queries and roughly 3 ms. Arbitrary client queries also need cost control. Assign each field a cost (lists multiply by their page size) and reject queries over a budget: a query requesting 100 users × 100 followers × 100 posts asks for a million objects and must be refused, however small it looks. Public GraphQL APIs typically rate-limit on these computed points rather than on request counts. Persisted queries, where the client sends a hash of a pre-registered query, add an allow-list, shrink requests, and make GET-based CDN caching possible.

What a persistent connection really costs. For WebSockets and SSE, sizing comes from memory and timers, not CPU:

  • Kernel socket buffers. Several KB per connection at minimum, more with default buffer sizes on busy sockets.
  • TLS session state. Commonly tens of KB per connection in typical libraries unless tuned.
  • Application state. User ID, subscriptions and the send buffer: anything from a few hundred bytes to many KB depending on language and framework.

At about 30 KB per connection, one million connections need about 30 GB of RAM. That's feasible on one large machine, but losing it disconnects a million users at once, so most designs spread connections over many smaller nodes. Heartbeats aren't free either. One million connections pinging every 30 seconds is about 33,000 small messages per second just to stay alive, and an idle-timeout mismatch with the load balancer (for example a 60-second LB idle timeout with 90-second pings) causes mysterious mass disconnects. Finally, plan for the reconnect storm. If a node holding 100,000 connections dies, those clients reconnect within seconds. Each reconnect performs authentication and a state fetch, so with no jitter the surge can be 10–100× normal login load. Jittered exponential backoff on the client and admission control on the server are mandatory.

Deep Dive: Sizing queues and streams: Little's law, backlogs, partitions and poison messagesShow

Little's law for queues. In a stable system, the average number of items in the system L equals the arrival rate λ times the average time each spends in it W: L = λW (Little, 1961). For a job queue this connects three quantities you can measure. If jobs arrive at 2,000 per second and each spends 0.5 seconds waiting plus running, about 1,000 jobs are in the system on average. If you need 1,000 jobs in flight concurrently and each worker process handles 10 concurrent jobs, you need at least 100 worker processes, plus headroom for peaks and failures. And as utilisation ρ approaches 1, queueing delay grows roughly like ρ/(1−ρ) in simple models. Workers at 90% utilisation see about 9× the delay of workers at 50%, so size for 60–70% at peak.

Backlogs and drain time. When consumers fall behind, the backlog grows at (arrival rate − processing rate). Once processing recovers, it drains at (processing rate − arrival rate). Worked example in the spirit of Slack's numbers: jobs arrive at 33,000 per second and average 1 KB. A one-hour slowdown that halts execution accumulates 33,000 × 3,600 ≈ 119 million jobs, about 119 GB. That's far more than most Redis nodes are provisioned for, and Redis needs headroom for bookkeeping on top. On Kafka it's a modest amount of disk spread over brokers, well inside a two-day retention window. If workers can then process 50,000 per second while 33,000 per second keep arriving, the backlog drains at 17,000 per second: 119 million ÷ 17,000 ≈ 7,000 seconds, nearly two hours. Two lessons follow. Keep the backlog in disk-backed storage, and keep surge capacity in the consumer fleet, because drain time is set by the excess over the arrival rate, not by total capacity.

Consumer lag as the autoscaling signal. For logs, consumer lag (the latest offset minus the committed offset, summed over partitions) is the key metric. Divide lag by the consumption rate to get time to catch up. "Lag of 3 million events" means little; "4 minutes behind and rising" is actionable. Autoscale consumers on lag (KEDA does this on Kubernetes), but remember the ceiling: in a Kafka consumer group, at most one consumer per partition is active. Extra consumers sit idle.

Choosing a partition count. A partition is Kafka's unit of ordering and of parallelism. Size it from throughput: partitions ≥ max(target throughput ÷ per-partition produce throughput, target throughput ÷ per-partition consume throughput). If the stream peaks at 200 MB/s and one consumer instance processes 10 MB/s of this data (the processing, not Kafka, is usually the limit), you need at least 20 partitions. Choose 40–60 for growth, because increasing partitions later changes the key-to-partition mapping and breaks per-key ordering for in-flight data. Don't go wild either. Each partition costs file handles, replication traffic and controller metadata, and very large partition counts lengthen failover and rebalancing. Modern KRaft-based clusters handle far more partitions than ZooKeeper-based ones did, but thousands per topic is rarely justified.

Ordering versus parallelism. Strict global order means one partition, which means one consumer, which caps throughput at whatever one consumer can do. Almost every system only needs per-key order: all events for one order, account or chat in sequence. Hash the key to a partition and you get both order and parallelism. Hot keys then become the risk. A celebrity account or a flash-sale item can push one partition far beyond the rest. Mitigations are splitting hot keys (add a suffix and merge downstream) or processing them on a separate path. On SQS FIFO the equivalent knob is the message group ID: order holds within a group, and groups are processed in parallel.

Visibility timeouts, acks and duplicates. In a queue, a message received but not acknowledged within the visibility timeout becomes visible again and is redelivered. Set the timeout above the 99.9th-percentile processing time with margin, or extend it with heartbeats for long jobs. If it's too short, slow jobs run twice concurrently; if it's too long, a crashed worker's jobs wait needlessly. Both problems point to the same requirement: idempotent processing. Keep a processed-IDs table with a unique constraint, use conditional writes, or make operations naturally idempotent (set, not increment). Idempotency and Safe Retries shows the patterns.

Poison messages and dead-letter queues. A message that always fails (malformed payload, a bug triggered by one input) is retried forever, wasting capacity, and in a log it blocks its partition, because the consumer can't advance past it.

  • In queues: set a maximum receive count (for example 5) after which the broker moves the message to a dead-letter queue (DLQ). Alert on DLQ depth, and build a redrive tool.
  • In logs: catch the failure and publish the event to a retry topic (orders.retry.1m, orders.retry.10m) consumed with a delay, then to a DLQ topic, and commit the original offset so the partition keeps moving. This is the pattern Slack's relay used when it re-enqueued failed jobs to Kafka.
  • Classify errors. Transient errors (timeouts, 503s) deserve retries with exponential backoff and jitter; permanent errors (validation failures) should dead-letter immediately.

Flow control. RabbitMQ's prefetch (basic.qos) caps unacknowledged messages per consumer. Without it, a single consumer can grab thousands of messages, starving others and losing them all to redelivery if it crashes; prefetch values of 10–100 are typical. Kafka consumers control batch size (max.poll.records) and must call poll within max.poll.interval.ms, or they're considered dead and their partitions rebalance away. Long per-message processing therefore needs either small batches or asynchronous processing with careful offset commits.

Deep Dive: Compute economics, cold starts and the build-vs-buy calculationShow

Inside serverless isolation. AWS Lambda runs functions in Firecracker microVMs. Firecracker: Lightweight Virtualization for Serverless Applications (Agache et al., NSDI 2020) describes a minimal virtual machine monitor that boots a microVM in roughly 125 ms with only a few MB of memory overhead. That gives VM-level isolation between tenants with container-like density and start time. Cloudflare Workers take a different route: V8 isolates inside one process, starting in a few milliseconds but limited to JavaScript, WebAssembly and languages compiled to them. The isolation model sets the cold-start floor.

A cold start has several parts:

  • creating or reusing a sandbox;
  • downloading and unpacking the code package or container image;
  • starting the language runtime;
  • running your initialisation code: loading the framework, opening database connections, reading secrets.

The first two are the platform's job. The last two are often the largest and fully under your control. A Node.js or Python function with few dependencies typically cold-starts in a few hundred milliseconds. A JVM application with a large framework can take seconds. Mitigations include:

  • trimming dependencies and moving lazy work out of init;
  • provisioned concurrency, which keeps N instances warm and is billed whether used or not;
  • snapshot-based approaches such as Lambda SnapStart, which restore an initialised memory snapshot;
  • choosing lighter runtimes for latency-sensitive paths.

If p99 latency matters and traffic is spiky enough to cause frequent cold starts, measure the cold-start rate, not just its duration. One cold start per 1,000 requests at 1.5 s may break a 500 ms p99.9 target even though p99 looks fine.

Connection management is the hidden serverless cost. Each concurrent function instance opens its own database connections. A traffic spike to 2,000 concurrent invocations can try to open 2,000 PostgreSQL connections, far beyond what a primary handles well (hundreds, with a pooler in front). Put a connection proxy between them (RDS Proxy, PgBouncer), cap function concurrency, or use databases with HTTP-based, connectionless APIs (DynamoDB, or serverless drivers for some managed SQL services).

A break-even model. Let R be requests per second, d the duration in seconds, m the memory in GB, p₁ the price per GB-second and p₂ the price per request. Monthly function cost is about 2.6M × R × (d × m × p₁ + p₂), since a month has about 2.6 million seconds. For containers, busy concurrency is R × d. With each instance serving c concurrent requests at a target utilisation u, you need N = ⌈R × d ÷ (c × u)⌉ instances, with a minimum of 2 for availability, each at monthly price P.

Function cost grows linearly with traffic from zero. Container cost is a step function with a floor. Below the crossover (low or intermittent traffic) functions win, often by a lot. Above it (sustained traffic) containers win, increasingly so as you raise utilisation with good bin-packing, autoscaling and spot or committed-use discounts.

Using the earlier prices, a 512 MB, 100 ms function costs about $0.0000010 per invocation in compute plus $0.0000002 per request: about $1.04 per million requests in compute, $1.24 per million in total. A small container instance at, say, $30 a month serving 100 requests per second sustained handles about 260 million requests a month, roughly $0.12 per million. The function is about ten times more expensive per request if the container is busy. If the container idles at 2% utilisation, the comparison flips. The real question is how much of the time your capacity would sit idle.

Containers' hidden costs. Containers aren't free either:

  • Platform overhead. Control plane fees, system daemons on every node (logging, monitoring, networking agents), and the engineers who run the platform.
  • Low utilisation. Many Kubernetes clusters run at 20–40% average CPU utilisation because requests are set conservatively. Right-sizing requests and enabling autoscaling of both pods and nodes often cuts cost by a third or more.
  • Data transfer. Cross-zone traffic between services, load balancers and replicas is billed in most clouds. A chatty service pair split across zones can cost more in transfer than in compute.

Cloud Architecture Essentials covers cost optimisation more broadly.

Quantifying build vs buy. Make it an explicit calculation over three years:

  • Build: initial engineering (engineers × months × loaded monthly cost), multiplied by an estimation-error factor (1.5–3× is realistic for infrastructure), plus annual maintenance (commonly 15–25% of the initial effort every year), plus infrastructure, plus on-call burden, plus opportunity cost (what those engineers would otherwise ship).
  • Buy: subscription at projected usage (model per-seat, per-MAU and per-event pricing at 1×, 3× and 10×), plus integration effort, plus vendor-management and compliance work, plus an exit-cost estimate.

Example: building an in-house feature-flag service with targeting rules, an audit log, SDKs in four languages and 99.99% availability. Estimate two engineers for six months to build, at a loaded $20,000 per engineer-month ($240,000), times 1.5 for underestimation ($360,000), plus 20% a year in maintenance ($72,000 a year). That's about $500,000 over three years before infrastructure. A commercial service at $3,000 a month costs $108,000 over the same period. Buying wins unless feature flags are strategically central, or usage-based pricing at your scale would run into the hundreds of thousands per year. Rerun the calculation at 10× scale before signing: usage-based pricing is where "buy" decisions turn sour.

Wardley-style thinking about evolution. Technologies move from novel to commodity over time. Ten years ago, running a message broker or a container orchestrator was a differentiating capability; now both are utilities you rent. A useful habit is to ask where each component sits on that curve. Build only things that are still novel and core to your product. Use products for maturing categories. Rent utilities for commodities. The boring stack is simply the set of components that have reached the commodity end.

Key Takeaways#

  • Choose by requirement → property → category → product, and filter by fit, team familiarity, operational cost and maturity, in that order.
  • REST + JSON is the default for public APIs; gRPC fits internal high-volume, polyglot calls (with L7 or client-side load balancing); GraphQL fits many diverse clients over overlapping data, with cost limits and batching.
  • For realtime, climb the ladder only as far as the requirement needs: polling → long polling → SSE → WebSockets → WebRTC (for media). Polling against a cache is often enough; WebSockets need connection routing, draining and reconnect-storm planning.
  • Queues carry commands to one worker, with per-message acks; logs carry facts to many consumers, with replay. Many systems use both.
  • SQS for zero-operations job queues, RabbitMQ for routing-heavy jobs, Kafka for high-throughput event streams with fan-out and replay. Every option delivers at least once, so consumers must be idempotent.
  • Redis is the default cache and ephemeral-state store; Memcached fits huge, simple caches. Design for memory limits, hot keys and single-threaded execution.
  • Containers for steady, long-running services; functions for spiky, short, event-triggered work. Cost and cold starts decide the boundary.
  • Buy or rent commodity capabilities; build what differentiates you. Quantify both sides over several years and at 10× scale.
  • Start from a boring default stack and spend innovation tokens only where a requirement forces it, as Slack did when a memory-bound queue failed and they put a durable log in front of it.