Building blocks 127 problems you will be handed in an interview, the most basic fix for each, and the tools to name. Say the problem and the property you need before you say the tool. 127 of them have a deep dive: how it works, a worked example, variants, failure modes and interviewer follow-ups.
How to revise with this Turn on Quiz mode to hide the solutions and start a follow-up drill drawn from the deep dives. Filter by category to drill one area, or search for a tool to see every problem it solves. Prefer a guided order? Try a study path .
All 127 Latency & performance 19 Scaling & load 10 Decoupling & async work 12 Storage & data modelling 16 Consistency & coordination 13 Reliability & failure handling 14 Networking & delivery 9 Real-time & streaming 9 Data processing & search 7 Security & abuse 8 Observability & operations 10
Latency & performance Make the common request faster.
The same data is read far more often than it changes and every read hits the database.
Basic solution
Put a cache in front of the store. Read the cache first; on a miss, read the DB and write the result back with a TTL (cache-aside ).
Tools to name
Redis Memcached in-process LRU DynamoDB DAX
Watch out
Invalidation on writes, stale reads until TTL , and a cold cache after restart.
A record is updated or deleted but the cache keeps serving the old value until its TTL runs out.
Basic solution
On every write, delete (not update) the cache key for that record, then let the next read repopulate it. Add a short TTL as a safety net and version the key when the shape changes.
Tools to name
delete-on-write short TTLs versioned keys CDC-driven invalidation
Watch out
Write DB then delete cache; a read racing between the two can re-cache stale data , so keep TTLs short.
Cache-aside leaves a window where the cache is stale after an update.
Basic solution
Write-through updates cache and DB in the same request; write-behind updates the cache and flushes to the DB asynchronously.
Tools to name
Redis Hazelcast Caffeine
Users far from your servers wait on round trips for images, scripts, video segments .
Basic solution
Put a CDN in front of the origin . Content is cached at points of presence near users; the origin only sees misses.
Tools to name
Cloudflare CloudFront Akamai Fastly
Watch out
Only cache what is safe to share; purge or version URLs when content changes.
A single primary database cannot keep up with read traffic.
Basic solution
Replicate the primary to one or more read replicas and route read-only queries to them.
Tools to name
Postgres streaming replication MySQL replicas Aurora readers
A query scans the whole table to find a few rows.
Tools to name
B-tree hash index GIN / inverted index EXPLAIN ANALYZE
Watch out
Every index slows writes and takes space; too many indexes is its own problem.
A query is slow and nobody knows whether it is the index , the join order or the row count.
Basic solution
Run EXPLAIN ANALYZE and read it bottom-up: look for sequential scans on big tables, nested loops over large sets, and estimated rows far from actual rows (stale statistics).
Tools to name
EXPLAIN ANALYZE pg_stat_statements slow query log ANALYZE to refresh stats
Watch out
A plan that is fast on a dev database can flip on production data sizes; test with realistic volume.
An index on status with three values barely narrows the rows, so the planner ignores it.
Basic solution
Put the most selective column (many distinct values) first in a composite index , and match the index order to the WHERE and ORDER BY. Use partial indexes for the rare value you actually query.
Tools to name
composite index column order partial indexes covering indexes cardinality stats
Watch out
Leading-column rule: an index on (a, b) does not help a query that filters only on b.
Each request opens a new DB connection, which is slow and exhausts the server.
Basic solution
Keep a pool of open connections per app instance and borrow one per request.
Tools to name
PgBouncer HikariCP RDS Proxy ProxySQL
Watch out
Pool size × instances must stay under the database connection limit.
A hot read path needs a multi-table join every time.
Tools to name
materialised views wide-column tables Elasticsearch documents
Watch out
Writes now update several places; keep them in one transaction or accept brief inconsistency.
Assembling a page at read time (a feed, a dashboard) is too slow.
Basic solution
Do the work when the data changes and store the result per user, so a read is a single fetch (fan-out on write).
Tools to name
Redis lists / sorted sets background workers Kafka consumers
Responses are large and the network is the bottleneck.
Basic solution
Compress responses, use binary encodings for internal traffic, and return only the fields the client asked for.
Tools to name
gzip / Brotli Protobuf GraphQL field selection sparse fieldsets
Watch out
CPU cost of compression; do not compress already-compressed media.
Thousands of tiny calls (N+1 queries , one Redis GET per id) dominate latency.
Basic solution
Collect ids and issue one bulk request: MGET, IN (...) queries, batched RPCs.
Tools to name
Redis MGET / pipelining DataLoader SQL IN lists gRPC streaming
A cache miss on a hot key sends hundreds of identical queries to the database at once.
Basic solution
Let the first request fetch and make the others wait for its result (single-flight / request coalescing).
Tools to name
singleflight (Go) promise memoisation CDN request collapsing
Watch out
Only safe for idempotent reads; waiters inherit the first request’s failure.
A popular key expires and every request misses at once, flattening the database (dog-piling ).
Basic solution
Serve the stale value while one request refreshes it, lock the refresh so only one caller fetches, and stagger TTLs with jitter so keys do not expire together.
Tools to name
stale-while-revalidate refresh lock / single-flight TTL jitter early probabilistic refresh
Watch out
A warm-up on deploy still misses everything; pre-populate the hottest keys.
Average latency looks fine while a slice of users wait seconds; a page that fans out to 100 services is as slow as the slowest one (tail latency amplification).
Basic solution
Track percentiles per endpoint and per dependency. Cut the tail with hedged requests (send a second copy after p95 and take the first reply), tighter timeouts, and fewer fan-out calls.
Tools to name
histograms (Prometheus, HDR) hedged requests per-call deadlines request fan-out limits
Watch out
Hedging doubles load on an already slow dependency; cap it to a few percent of requests.
One celebrity record or one counter overwhelms the single cache node that owns it.
Basic solution
Replicate the key under suffixed names (key#0..N) and read a random copy; or add a tiny in-process cache in each app server.
Tools to name
local caches (Caffeine, Guava) key suffixing Redis replicas
Watch out
Copies drift until the next refresh; write all copies or use short TTLs .
A server thread sits idle waiting on the network while other requests queue.
Basic solution
Use non-blocking I/O or an event loop so one process handles many concurrent connections.
Tools to name
Node.js Netty Go goroutines Tokio asyncio
Watch out
CPU-heavy work still needs threads or a worker pool.
Scaling & load Serve more traffic and more data than one machine can.
One server cannot handle the request rate, or a single server is a single point of failure.
Tools to name
nginx HAProxy AWS ALB / NLB Envoy
Sessions or files stored on a server mean requests must return to the same machine.
Basic solution
Move state out: sessions to Redis or signed cookies, files to object storage , so any server can serve any request.
Tools to name
JWT Redis sessions S3
Watch out
Signed tokens cannot be revoked instantly; keep them short-lived.
A bigger machine is expensive, has a ceiling, and is still one machine.
Basic solution
Add more commodity instances behind a balancer and autoscale on CPU, queue depth or request rate.
Tools to name
Kubernetes HPA AWS Auto Scaling ECS
Watch out
Only works once the service is stateless and the data layer scales too.
One database holds more data or takes more writes than a single node can handle.
Basic solution
Split rows across shards by a key (user id, tenant, hash of id). Each shard is a smaller database.
Tools to name
hash sharding range sharding Vitess Citus Cassandra partitions
Watch out
Cross-shard queries and transactions are hard; pick the key so hot paths stay on one shard .
Modulo hashing (key % N) remaps almost every key when N changes.
Basic solution
Place nodes and keys on a hash ring ; a key belongs to the next node clockwise. Adding a node moves only about 1/N of the keys. Virtual nodes smooth the load.
Tools to name
consistent hashing rendezvous hashing Ketama
Watch out
Hot keys are still hot; clients must learn ring changes.
One partition takes most of the traffic (a celebrity, a popular tenant, a time-ordered key).
Basic solution
Choose a key with better spread, add a random or hashed prefix to spread sequential keys, or split the hot partition .
Tools to name
salted keys compound partition keys range splitting
Watch out
Salting breaks range scans; you now read N sub-partitions.
Traffic is naturally local (a city, a country) and cross-region latency hurts.
Basic solution
Partition data and services by geography so a request is served entirely within its region.
Tools to name
region shards geo DNS cell-based architecture
Watch out
Users and objects that move between regions; one region down must not take the rest.
Clients must know every service, and cross-cutting concerns (auth, limits, TLS ) are duplicated.
Tools to name
Kong AWS API Gateway Envoy nginx
Watch out
The gateway is on every request’s path; keep it thin and redundant.
Teams block each other in one codebase and one deploy; one hot path cannot scale independently.
Basic solution
Split along business boundaries into services that own their data and communicate over APIs or events.
Tools to name
gRPC REST service mesh (Istio, Linkerd)
Watch out
Distributed transactions, network failures, and operational overhead. Start with a modular monolith.
Images, videos and uploads bloat the database and the app servers.
Tools to name
S3 GCS Azure Blob MinIO
Watch out
No transaction spans the database row and the blob, so a row can point at a blob that never finished uploading; verify on completion and delete orphans with lifecycle rules.
Decoupling & async work Stop one component from waiting on, or breaking, another.
The request path waits on slow work (email, resize, analytics) or on a service that may be down.
Basic solution
Put a queue between them. The producer enqueues and returns; workers consume at their own pace.
Tools to name
SQS RabbitMQ Kafka Google Pub/Sub
Several systems need to react to the same event, and the producer should not know about them.
Basic solution
Publish to a topic; each subscriber gets its own copy (pub/sub ). Add subscribers without touching the publisher.
Tools to name
Kafka topics SNS + SQS Redis Pub/Sub Google Pub/Sub
Watch out
Redis Pub/Sub does not persist; use a log (Kafka) when subscribers may be offline.
Consumers need to re-read history, or new consumers need to catch up from the start.
Basic solution
Use a partitioned, append-only log with retention. Consumers track their own offset and can rewind.
Tools to name
Kafka Pulsar Kinesis Redpanda
Watch out
Ordering is per partition only; choose the partition key to keep related events together.
A request takes seconds because it does everything inline.
Basic solution
Return quickly (202 Accepted) and do the heavy part in a worker; expose status for the client to poll or push a notification when done.
Tools to name
Celery Sidekiq BullMQ Temporal
Watch out
The client needs a way to learn the outcome; design the status model up front.
A retried request or redelivered message creates a duplicate order, charge or notification.
Basic solution
Have the caller send an idempotency key ; store it with the result and return the stored result on repeats.
Tools to name
Idempotency-Key header Redis SET NX unique constraints
Watch out
Keys need a TTL and a scope (per user); a crash between side effect and record still leaves a window.
Writing to the database and publishing to Kafka are two steps; one can succeed without the other.
Basic solution
Write the event into an outbox table in the same transaction; a relay reads the outbox and publishes (transactional outbox).
Tools to name
Debezium outbox table + poller CDC
Watch out
The relay delivers at least once ; consumers dedupe on event id.
Other systems (search, cache, analytics) must stay in sync with the database without the app publishing for each one.
Basic solution
Tail the database’s change log and emit each row change as an event (change data capture ).
Tools to name
Debezium DynamoDB Streams Postgres logical replication
Watch out
Consumers see row diffs, not domain events; schema changes ripple downstream.
One malformed message fails forever and blocks or wastes a worker.
Basic solution
After N failed attempts move it to a dead-letter queue , alert, and replay after fixing.
Tools to name
SQS DLQ RabbitMQ dead-letter exchange Kafka retry topics
Watch out
Someone must own the DLQ ; an unwatched DLQ is silent data loss.
A marketing blast of 10M messages delays a password-reset email.
Basic solution
Separate queues (or partitions ) per priority and per channel, with their own worker pools and limits.
Tools to name
per-priority queues SQS FIFO + standard weighted consumers
Watch out
Strict priority can starve the low lane; use weights.
Send at 9am local time, expire links nightly, retry in 10 minutes.
Basic solution
Store jobs with a due time and have a scheduler enqueue them when due; or use delayed messages.
Tools to name
cron Quartz SQS delay Redis sorted set by due time Temporal
Watch out
Exactly-once firing needs a lock or a claim so two schedulers do not both run it.
An order touches payment, inventory and shipping services; no single transaction spans them.
Basic solution
Run a saga : a sequence of local transactions, each with a compensating action to undo it on failure.
Tools to name
orchestration (Temporal, Step Functions) choreography via events
Watch out
Compensations are not rollbacks; the intermediate state is visible.
Third parties poll your API for status, or you poll theirs.
Basic solution
Register a callback URL; the sender POSTs an event when something happens. Sign it and retry with backoff .
Tools to name
HMAC-signed webhooks Svix retry with backoff
Watch out
Receivers must be idempotent and fast (ack then process).
Storage & data modelling Pick the store and the shape of the data for the access pattern.
Structured data with relationships, transactions and ad-hoc queries.
Basic solution
Use Postgres or MySQL. It covers most products to a few TB with replicas and indexes .
Tools to name
Postgres MySQL Aurora CockroachDB
Watch out
Horizontal write scaling needs sharding , which is manual.
The access pattern is "get by id" and "put by id" at very high volume.
Basic solution
Use a key-value store that partitions by key automatically.
Tools to name
DynamoDB Redis Riak etcd (small, consistent)
Watch out
Secondary queries need extra indexes or a second store.
Billions of rows written in order and read as ranges per key (messages, events, sensor data).
Tools to name
Cassandra ScyllaDB HBase Bigtable
Watch out
Design tables per query; no joins, weak transactions, tombstones on delete.
Records have varying shapes and are read whole (a product, a profile).
Basic solution
Store each record as a JSON document and index the fields you query.
Tools to name
MongoDB Couchbase Postgres JSONB
Watch out
Easy to end up with inconsistent shapes; validate at the edge .
High write rate of timestamped points, queried by time range and aggregated.
Basic solution
Use a time-series database with compression and downsampling.
Tools to name
InfluxDB TimescaleDB Prometheus ClickHouse
Watch out
Cardinality explosion from too many label combinations.
"Friends of friends who like X" is many joins in SQL.
Basic solution
Use a graph database when traversals are the main query; otherwise an adjacency table in SQL is enough.
Tools to name
Neo4j Neptune adjacency lists in Postgres
Watch out
Most "graph" needs (followers , following) are fine as two indexed tables.
LIKE "%term%" cannot rank, tokenise or tolerate typos.
Tools to name
Elasticsearch OpenSearch Meilisearch Postgres tsvector
Reporting queries scan millions of rows and slow the transactional database.
Basic solution
Copy data to a column store built for aggregation and run analytics there.
Tools to name
ClickHouse BigQuery Snowflake Redshift Druid
Watch out
Data arrives with a delay; not for per-request reads.
Choosing an engine for a heavy write load vs a heavy read load.
Basic solution
LSM trees batch writes in memory and flush sorted runs (fast writes, slower reads, compaction ). B-trees update in place (fast point reads, more random writes).
Tools to name
RocksDB / LevelDB (LSM) InnoDB / Postgres (B-tree)
Watch out
LSM compaction causes write stalls and space amplification.
One logical write turns into many physical writes: WAL plus page, every index , every replica , and LSM compaction rewriting the same data several times.
Basic solution
Count the writes a row costs (indexes × replicas × compaction levels), drop indexes you do not query, batch small writes, and pick an engine whose amplification fits the workload.
Tools to name
fewer indexes batched writes tiered vs levelled compaction append-only logs
Watch out
SSD wear and I/O saturation show up long before CPU does on write-heavy systems.
One logical read touches many places: several LSM levels, a cache miss then the DB, a fan-out to N shards , or N+1 queries .
Basic solution
Make the common read a single lookup: denormalise , cache the assembled result, keep per-key data on one shard , and use Bloom filters so missing keys skip disk.
Tools to name
Bloom filters denormalised read models single-shard access patterns MGET batching
Auto-increment ids need one database; UUIDs are random and index poorly.
Basic solution
Use time-ordered ids: a timestamp plus node id plus sequence (Snowflake ), or ULID / UUIDv7.
Tools to name
Snowflake ULID UUIDv7 KGS pre-generated keys
Watch out
Clock skew between nodes; ids leak creation time.
Sessions, links and tokens must disappear after a while without a cleanup job.
Basic solution
Store an expires_at and set a TTL on the row or key; check on read (lazy) and sweep in the background (active).
Tools to name
Redis EXPIRE DynamoDB TTL Cassandra TTL cron sweeper
Watch out
TTL deletion is best-effort and delayed; still check on read.
Deleted rows must be recoverable, audited, or filtered out of caches already fanned out.
Basic solution
Set a deleted_at tombstone instead of removing the row; filter it on read and purge later.
Tools to name
deleted_at columns tombstones archival tables
Watch out
Every query must filter tombstones ; unique constraints need care.
Adding a column or changing a type locks a huge table.
Basic solution
Expand-then-contract: add the new column nullable, backfill in batches, switch reads, then drop the old one.
Tools to name
gh-ost pt-online-schema-change Flyway Liquibase
Watch out
Two code versions run at once during a deploy; both must tolerate both schemas.
One store is asked to be both a transactional index and a petabyte blob store .
Basic solution
Keep small, queryable metadata in a database and large immutable bytes in object storage , linked by key.
Tools to name
Postgres + S3 DynamoDB + S3
Watch out
Two writes per upload; validate the blob exists before marking metadata ready.
Consistency & coordination Agree on one truth across many nodes.
A user posts, refreshes, and the post is missing because the read hit a lagging replica .
Basic solution
Route reads for a short window after a write to the primary (or to a replica that has caught up), using a session marker such as the last write’s LSN or timestamp.
Tools to name
sticky-to-primary after write LSN / version tokens in the session causal consistency
Watch out
Only the writer needs this guarantee; other users can tolerate the lag.
When nodes cannot talk, do you refuse writes or accept divergent ones?
Basic solution
Decide per feature. Balances and inventory favour consistency (refuse); likes and presence favour availability (accept and reconcile).
Tools to name
CP stores (Spanner, etcd, Zookeeper) AP stores (Cassandra, Dynamo)
Watch out
Most systems are tunable per request; say which operations need which.
Keeping every replica identical on every write is slow and fragile.
Basic solution
Let replicas converge asynchronously; design the UI so a few hundred milliseconds of staleness is fine.
Tools to name
async replication read-your-writes routing optimistic UI
Watch out
Name the user-visible anomaly (a just-created link may take a moment).
You want strong reads sometimes and fast writes other times on a replicated store.
Basic solution
With N replicas , write to W and read from R; R + W > N guarantees a read sees the latest write.
Tools to name
Cassandra consistency levels DynamoDB strongly consistent reads
Watch out
Higher quorums raise latency and reduce availability during failures.
Nodes must agree on configuration, leadership or a lock even when some crash.
Tools to name
etcd ZooKeeper Consul Raft Paxos
Watch out
Consensus is for small, critical metadata, not for high-volume data.
Two workers both try to match the same driver, run the same job, or process the same file.
Basic solution
Take a lease : SET key NX with a TTL , do the work, release. Or route all work for a key to a single owner.
Tools to name
Redis SET NX PX ZooKeeper ephemeral nodes DB row locks single consumer per partition
A worker holding a lease pauses (GC, network), the lease expires, another worker takes it, then the first wakes up and writes anyway.
Basic solution
Issue a monotonically increasing token with each lease and have the storage reject writes carrying a token older than the latest it has seen.
Tools to name
fencing tokens ZooKeeper zxid etcd revisions conditional writes on version
Watch out
The protected resource must check the token; a lock alone cannot stop a zombie writer.
Two users edit the same record; the last write silently wins.
Basic solution
Store a version; update WHERE version = expected and reject if zero rows changed (compare-and-set ).
Tools to name
version columns ETags / If-Match DynamoDB conditional writes Redis WATCH
Watch out
Clients need a retry path; under heavy contention use a lock or a queue instead.
Contention is high (one hot inventory row, one account) and optimistic retries keep failing.
Basic solution
Take the lock first: SELECT ... FOR UPDATE inside the transaction, change the row, commit. Waiters queue instead of retrying.
Tools to name
SELECT FOR UPDATE SKIP LOCKED for job queues advisory locks
Watch out
Holding locks across network calls causes deadlocks and timeouts; keep the critical section tiny.
Messages or events arrive out of order across servers with skewed clocks.
Basic solution
Assign a per-stream sequence number from a single owner and let clients detect gaps.
Tools to name
per-partition offsets per-conversation counters Lamport / vector clocks
Watch out
Global ordering across streams is expensive; only order where the product needs it.
Two requests read the same counter and both write +1, losing an increment.
Basic solution
Use an atomic primitive: INCR, a Lua script, a conditional update, or a transaction.
Tools to name
Redis INCR / EVALSHA SQL UPDATE ... SET n = n + 1 CAS
Watch out
Atomic on one node is not atomic across shards .
A single operation must succeed in two databases or neither.
Tools to name
XA transactions Spanner sagas as the alternative
Watch out
Blocks while the coordinator is down; slow; rarely worth it.
Ordering, expiry and rate limits based on client timestamps are wrong when clocks drift.
Basic solution
Use server time for anything that matters; use monotonic clocks for intervals; NTP all servers.
Tools to name
Redis TIME hybrid logical clocks TrueTime (Spanner)
Watch out
Even server clocks drift; design for a few hundred ms of skew.
Reliability & failure handling Keep working when parts fail.
A timeout or 503 fails the whole request, or naive retries pile on a struggling service.
Tools to name
exponential backoff + jitter retry budgets Retry-After header
Watch out
Retries at every layer multiply load; cap total attempts across the stack.
A hung downstream call ties up threads until the whole service stalls.
Basic solution
Set a timeout on every network call, shorter than the caller’s own deadline, and propagate deadlines.
Tools to name
connect / read timeouts gRPC deadlines context cancellation
Watch out
A timeout is not a failure of the remote side; the work may still complete there.
A dead service makes every caller wait for a timeout, cascading the outage.
Basic solution
Track failures; after a threshold open the circuit and fail fast, probing occasionally to close it again.
Tools to name
Resilience4j Hystrix (retired) Envoy outlier detection
Watch out
Decide what fail-fast returns: an error, a cached value, or a degraded default.
The rate limiter , auth cache or feature-flag service is unreachable.
Basic solution
Fail open (allow) for availability-first features; fail closed (deny) for security-sensitive ones. Decide per endpoint.
Tools to name
local fallbacks cached decisions static defaults
Watch out
Fail-open on login or payments is an incident waiting to happen.
One slow tenant or one slow endpoint consumes all threads and starves the rest.
Basic solution
Partition resources: separate pools, queues or instances per tenant, priority or dependency.
Tools to name
thread pools per dependency separate queues cells
Watch out
Smaller pools mean each partition has less headroom.
A non-critical part (recommendations, ads, analytics) is down and takes the page with it.
Basic solution
Make non-critical calls optional: timeouts with defaults, feature flags to switch them off, cached last-known-good.
Tools to name
feature flags fallback responses stale-while-revalidate
Watch out
Know which features are critical before the incident, not during.
Traffic exceeds capacity and every request slows until all time out.
Basic solution
Reject excess requests early (429 or 503) based on queue depth or latency so the rest succeed.
Tools to name
admission control queue length limits adaptive concurrency limits
Watch out
Shed the least valuable traffic first (bulk, anonymous, retries).
Accepting every request means all of them slow down together once the queue grows past what can be served within the deadline.
Basic solution
Bound in-flight work per service (concurrency limit) and reject new work when the bound is hit; adapt the limit from observed latency, and reject requests whose deadline has already passed.
Tools to name
adaptive concurrency limits (Netflix) CoDel-style queue timeouts per-tenant quotas deadline propagation
Watch out
Rejecting early looks worse on a dashboard than queueing, but it keeps the successful requests fast.
A single database or cache node dies and the service goes down with it.
Tools to name
leader / follower replication Redis Sentinel RDS Multi-AZ Patroni
A data-centre outage takes everything down.
Basic solution
Run in at least two availability zones ; for region loss, replicate data and fail over DNS to a second region.
Tools to name
multi-AZ deployments cross-region replication Route 53 failover
Watch out
Active-active across regions needs conflict handling; active-passive needs regular failover drills.
The load balancer keeps sending traffic to a crashed or overloaded server.
Basic solution
Expose liveness and readiness endpoints; the balancer or orchestrator removes failing instances and restarts them.
Tools to name
Kubernetes probes ALB health checks /healthz
Watch out
A health check that calls dependencies can take the whole fleet out when one dependency blips.
Thousands of clients or keys retry, reconnect or expire at the same instant.
Basic solution
Add jitter to retries, TTLs and reconnects; warm caches gradually; serve stale while refreshing.
Tools to name
jitter staggered TTLs stale-while-revalidate request coalescing
Watch out
Fixed-window rate limits and cron-aligned jobs are common herd sources.
A fast producer fills memory or queues faster than consumers drain them.
Basic solution
Bound buffers and make the producer wait, drop, or sample when they fill (backpressure ).
Tools to name
bounded queues TCP flow control Reactive Streams Kafka consumer lag alerts
Watch out
Unbounded queues turn an overload into an out-of-memory crash later.
Replication faithfully copies a bad migration or a DELETE without WHERE to every replica .
Tools to name
pg_basebackup + WAL archiving RDS PITR snapshots
Watch out
A backup you have never restored is a hope, not a backup.
Networking & delivery Get bytes to clients quickly and safely.
Global users should hit the closest region, and a dead region should be skipped.
Basic solution
Use latency-based or geo DNS with health checks , or anycast the same IP from many sites.
Tools to name
Route 53 latency routing Cloudflare anycast
Watch out
DNS caching delays failover ; keep TTLs short on failover records.
Every app server handles certificates and the TLS handshake cost.
Tools to name
ALB / nginx TLS Let’s Encrypt service mesh mTLS
Watch out
Internal traffic still needs protection in shared networks.
External clients want simple HTTP + JSON; internal services want speed and typed contracts.
Basic solution
REST / JSON for public APIs, gRPC with Protobuf between services, GraphQL when clients need flexible shapes.
Tools to name
REST gRPC GraphQL OpenAPI
Watch out
gRPC needs HTTP/2 end to end; GraphQL needs query cost limits.
Mobile apps in the wild call an old shape for years.
Basic solution
Only add fields; version the path or header when you must remove or change semantics; keep old versions for a sunset period.
Tools to name
/v1 paths Accept-Version header Protobuf field numbering
Watch out
Every live version is code you maintain; publish deprecation dates.
Uploads stream through API servers, which become a bandwidth bottleneck.
Tools to name
S3 pre-signed URLs multipart upload tus protocol
Watch out
Validate after upload (size, checksum, type) and garbage-collect abandoned parts.
One video file either buffers on slow links or wastes bandwidth on fast ones.
Basic solution
Transcode into several renditions, cut into short segments , and let the player switch quality per segment (HLS / DASH).
Tools to name
HLS MPEG-DASH FFmpeg CDN segment caching
Watch out
Segment length trades start-up latency against switching granularity.
Clients re-download unchanged resources on every visit.
Basic solution
Set Cache-Control with long max-age for versioned assets, ETag / Last-Modified for revalidation, and immutable for content-addressed files.
Tools to name
Cache-Control ETag content-hashed filenames
Watch out
A long max-age on an unversioned URL means users keep the old file.
Should the browser cache a redirect?
Basic solution
301 is permanent and cached (cheap, no analytics); 302 / 307 is temporary and re-requested every time (trackable, changeable).
Tools to name
301 302 307 308
Watch out
A cached 301 cannot be undone for returning users.
App servers handle TLS , compression, static files, buffering and slow clients themselves.
Basic solution
A reverse proxy handles those and forwards clean requests to the app.
Tools to name
nginx Envoy Caddy Traefik
Watch out
Header trust: only accept X-Forwarded-For from your own proxy.
Real-time & streaming Push changes to users and systems as they happen.
Chat, presence and live updates need server-to-client pushes, not polling.
Basic solution
Keep a persistent WebSocket per client on connection servers; route messages to the server that holds the user’s socket.
Tools to name
WebSocket Socket.IO connection registry in Redis
Watch out
Stateful connections need sticky routing, a registry, and reconnect-with-cursor logic.
You need server pushes but WebSockets are blocked or overkill.
Tools to name
SSE / EventSource long polling
Server A has a message for Bob, but Bob’s socket is on server C.
Basic solution
On connect, write user → server into a shared registry with a TTL ; look it up to route, or publish to a per-server channel.
Tools to name
Redis hash with TTL Redis Pub/Sub per server consistent hashing of users to servers
Watch out
Stale entries after crashes; refresh on heartbeat .
Broadcasting every status change to every contact is N² traffic.
Basic solution
Clients heartbeat every ~30 s; store last_seen with a TTL ; publish changes only to users who are currently subscribed (chat open).
Tools to name
Redis SET with TTL batched heartbeats subscription lists
Watch out
Typing indicators are transient: never store them.
Counts, windows and joins over a never-ending stream, with results in seconds.
Tools to name
Kafka Streams Flink Spark Structured Streaming ksqlDB
Watch out
Late and out-of-order events; define watermarks and window semantics.
"Drivers within 2 km" is a 2-D query that a B-tree cannot answer.
Basic solution
Encode location into cells (geohash , H3, S2) and query the target cell plus its neighbours; or use a spatial index .
Tools to name
Redis GEO H3 S2 PostGIS quadtrees for static points
Watch out
Boundary effects: always check neighbouring cells; moving points churn tree structures.
Every driver sends a location every few seconds.
Basic solution
Send updates to a partitioned stream, keep only the latest position per entity in memory, and reduce frequency when idle.
Tools to name
Kafka partitioned by region Redis GEO adaptive update intervals
Watch out
Last-writer-wins on timestamps; archive history separately.
The recipient has no connection; the message must arrive later and in order.
Basic solution
Write to a durable per-user inbox before pushing; on reconnect the client sends its last cursor and drains the inbox.
Tools to name
per-user inbox table / queue sync cursors silent push to wake the app
Watch out
Inbox growth for long-offline users; cap and fall back to history reads.
The app is closed; you cannot hold a socket.
Basic solution
Send through the platform push service using the device token; keep payloads small and fetch details on open.
Tools to name
APNs FCM Web Push
Watch out
Tokens expire and devices change; handle provider feedback and rate limits .
Data processing & search Compute over large data and find things in it.
Daily reports, model training and backfills over terabytes.
Basic solution
Run distributed batch jobs over data in object storage or a warehouse on a schedule.
Tools to name
Spark MapReduce Airflow dbt BigQuery
Watch out
Results are hours old; combine with streaming for freshness (lambda / kappa).
Analytics, search and ML each need a copy of production data in their own shape.
Basic solution
Extract from sources (CDC or dumps), transform, load into the target; schedule and monitor it as a DAG .
Tools to name
Airflow Fivetran Kafka Connect Debezium
Watch out
Schema drift and late data; make loads idempotent and replayable.
Unique visitors, top-k items or membership checks over billions of events.
Tools to name
Redis PFADD / PFCOUNT Bloom filter Count-Min Sketch top-k sketches
Watch out
Answers are approximate; state the error bound.
Chronological feeds bury the posts users care about.
Basic solution
Fetch candidates cheaply, score them with a model or heuristics, keep the top N; sit the ranker between the cache and the client.
Tools to name
feature store candidate generation + scoring learning-to-rank
Watch out
Keep a chronological fallback; ranking needs offline evaluation and logging.
At-least-once delivery double counts clicks, views and payments.
Basic solution
Carry a unique event id and keep a window of seen ids; or make the aggregate idempotent (set semantics).
Tools to name
Redis SET NX with TTL Bloom filters Kafka exactly-once with transactions
Watch out
The dedup window must outlast the retry window.
Prefix search over millions of terms in under 50 ms.
Basic solution
Build a trie or a sorted prefix index with precomputed top-k per prefix, held in memory and refreshed offline.
Tools to name
trie Elasticsearch completion suggester Redis sorted sets
Watch out
Fuzzy matching and personalisation multiply the index size.
Transcoding a long video or processing a large file takes hours on one worker.
Basic solution
Split into chunks, process chunks in parallel as a DAG of tasks with retries per task, then stitch.
Tools to name
FFmpeg Temporal / Step Functions Airflow worker pools
Watch out
Orchestrator state must be durable; prioritise by creator or deadline.
Security & abuse Keep out the wrong people and the wrong traffic.
One client (or a bot) floods the API and degrades it for everyone.
Tools to name
token bucket sliding window counter Redis + Lua API gateway limits
Watch out
Atomic read-modify-write; decide fail-open vs fail-closed when the store is down.
Who is calling, and are they allowed to do this?
Basic solution
Authenticate with sessions or signed tokens (JWT ) issued by an identity provider; authorise per resource with roles or policies at the service.
Tools to name
OAuth 2 / OIDC JWT session cookies RBAC / ABAC Auth0 / Cognito
Watch out
JWTs cannot be revoked before expiry; keep them short and pair with refresh tokens.
Machine clients need an identity to rate limit and bill.
Basic solution
Issue random API keys, store only their hash, and look up on each request; scope keys to permissions.
Tools to name
hashed API keys HMAC request signing key rotation
Watch out
Keys in URLs leak into logs; send them in headers.
Credentials in config files; sensitive data readable by anyone with disk access.
Basic solution
Keep secrets in a vault with rotation; encrypt data in transit (TLS ) and at rest (KMS-managed keys); hash passwords with a slow hash.
Tools to name
Vault AWS KMS / Secrets Manager bcrypt / Argon2 TLS everywhere
Watch out
Encryption at rest does not protect against an application-level bug.
Injection, oversized payloads and malformed input reach business logic.
Basic solution
Validate schema, size and type at the API boundary; use parameterised queries; reject early with 400.
Tools to name
JSON Schema parameterised SQL request size limits WAF
Watch out
Validate on the server even if the client already did.
Traffic far above capacity from thousands of sources.
Basic solution
Front everything with a CDN / scrubbing network, rate limit per IP and per key, and shed load at the edge.
Tools to name
Cloudflare AWS Shield WAF rules edge rate limits
Watch out
Application-layer attacks look like real users; need behavioural signals.
Malicious links, squatting on short aliases, fake accounts.
Basic solution
Score content and accounts asynchronously with rules and models, quarantine before publish when risk is high, and block lists at the edge .
Tools to name
Safe Browsing API reputation scores CAPTCHA allow / deny lists
Watch out
False positives hurt real users; keep an appeal path.
Users want messages the provider cannot read.
Basic solution
Encrypt on the client with keys the server never holds; the server routes and stores ciphertext only.
Tools to name
Signal protocol X3DH Double Ratchet
Watch out
Server-side search, moderation and multi-device sync become hard or impossible.
Observability & operations Know what the system is doing and change it safely.
You learn about outages from users.
Basic solution
Emit request rate, error rate, latency percentiles and saturation per service; alert on symptoms (SLO burn), not on every cause.
Tools to name
Prometheus + Grafana Datadog the four golden signals SLOs / error budgets
Teams argue about whether the system is reliable enough and whether to ship or stabilise.
Basic solution
Define an SLO (99.9% of requests succeed within 300 ms over 30 days). The allowed failures are the error budget ; alert when it burns too fast, and pause risky launches when it is spent.
Tools to name
SLIs / SLOs burn-rate alerts error budget policy
Watch out
Pick SLIs users feel (success rate, latency), not internal ones (CPU).
Grepping free-text logs across 200 servers during an incident.
Basic solution
Emit structured (JSON) logs with request id , user id and service, shipped to a central store.
Tools to name
ELK / OpenSearch Loki CloudWatch Logs
Watch out
Never log secrets or full PII; sample noisy debug logs.
A slow request touches ten services; which one is slow?
Basic solution
Propagate a trace id through every hop and record spans; view the request as a waterfall.
Tools to name
OpenTelemetry Jaeger Zipkin Honeycomb
Watch out
Sample traces at scale; make sure queues propagate context too.
Logs from ten services describe one failed request but nothing ties them together.
Basic solution
Generate a correlation id at the edge , pass it in a header and through queue messages, and include it in every log line and span so one search shows the whole story.
Tools to name
X-Request-ID W3C traceparent OpenTelemetry context propagation MDC / structured log fields
Watch out
Async hops drop context unless you put the id in the message envelope.
Every deploy is a big-bang release and rollback means redeploying.
Basic solution
Gate new behaviour behind flags; turn on for a percentage or a cohort; kill switch without a deploy.
Tools to name
LaunchDarkly Unleash config service
Watch out
Flags accumulate; delete them after rollout.
A bad deploy hits 100% of users at once.
Basic solution
Blue-green swaps traffic between two full environments; canary sends a small slice to the new version and watches error rates before widening.
Tools to name
rolling updates canary analysis Argo Rollouts ALB weighted targets
Watch out
Both versions run together; schema and API changes must be backward compatible.
Hard-coded hostnames and config files that need a redeploy to change.
Basic solution
Register instances in a discovery service and read config from a central, watched store.
Tools to name
Consul etcd Kubernetes DNS Eureka
Watch out
The config store is a dependency; cache the last good config locally.
How many servers, how much storage, how big a cache?
Basic solution
Start from DAU and actions per user, derive QPS (× peak multiplier), bytes per record × retention, and the hot fraction for cache; then add headroom.
Tools to name
back-of-envelope estimates load testing (k6, Locust) the Estimator page
Watch out
Peak is 3–10× average; design for peak and for one zone being down.
Failover , restores and runbooks are untested until the real incident.
Basic solution
Inject failures in a controlled way, run game days , and drill region failover and backup restores on a schedule.
Tools to name
Chaos Monkey Gremlin game days runbooks
Watch out
Start in staging with a blast-radius limit.