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.

Latency & performance

Make the common request faster.

Invalidate the cache when data changesfundamental

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-writeshort TTLsversioned keysCDC-driven invalidation
Watch out

Write DB then delete cache; a read racing between the two can re-cache stale data, so keep TTLs short.

Read the query plansenior

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 ANALYZEpg_stat_statementsslow query logANALYZE to refresh stats
Watch out

A plan that is fast on a dev database can flip on production data sizes; test with realistic volume.

Index selective columns firstsenior

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 orderpartial indexescovering indexescardinality stats
Watch out

Leading-column rule: an index on (a, b) does not help a query that filters only on b.

Pool database connectionsfundamental

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
PgBouncerHikariCPRDS ProxyProxySQL
Watch out

Pool size × instances must stay under the database connection limit.

Precompute joinsfundamental

A hot read path needs a multi-table join every time.

Basic solution

Store a copy of the joined result (denormalise) or maintain a materialised view updated on write.

Tools to name
materialised viewswide-column tablesElasticsearch documents
Watch out

Writes now update several places; keep them in one transaction or accept brief inconsistency.

Send fewer bytesfundamental

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 / BrotliProtobufGraphQL field selectionsparse fieldsets
Watch out

CPU cost of compression; do not compress already-compressed media.

Protect against a cache stampedesenior

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-revalidaterefresh lock / single-flightTTL jitterearly probabilistic refresh
Watch out

A warm-up on deploy still misses everything; pre-populate the hottest keys.

Measure p95 / p99, not the averagesenior

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 requestsper-call deadlinesrequest fan-out limits
Watch out

Hedging doubles load on an already slow dependency; cap it to a few percent of requests.

Spread a hot keysenior

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 suffixingRedis replicas
Watch out

Copies drift until the next refresh; write all copies or use short TTLs.

Do not block on I/Osenior

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.jsNettyGo goroutinesTokioasyncio
Watch out

CPU-heavy work still needs threads or a worker pool.

Scaling & load

Serve more traffic and more data than one machine can.

Keep servers statelessfundamental

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
JWTRedis sessionsS3
Watch out

Signed tokens cannot be revoked instantly; keep them short-lived.

Scale out, not upfundamental

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 HPAAWS Auto ScalingECS
Watch out

Only works once the service is stateless and the data layer scales too.

Partition the datafundamental

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 shardingrange shardingVitessCitusCassandra partitions
Watch out

Cross-shard queries and transactions are hard; pick the key so hot paths stay on one shard.

Fix a hot shardsenior

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 keyscompound partition keysrange splitting
Watch out

Salting breaks range scans; you now read N sub-partitions.

Shard by regionstaff

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 shardsgeo DNScell-based architecture
Watch out

Users and objects that move between regions; one region down must not take the rest.

Split a monolith by domainsenior

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
gRPCRESTservice mesh (Istio, Linkerd)
Watch out

Distributed transactions, network failures, and operational overhead. Start with a modular monolith.

Keep large blobs out of the databasefundamental

Images, videos and uploads bloat the database and the app servers.

Basic solution

Store blobs in object storage and keep only the key and metadata in the database. Upload directly with pre-signed URLs.

Tools to name
S3GCSAzure BlobMinIO
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.

Make retries safefundamental

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 headerRedis SET NXunique constraints
Watch out

Keys need a TTL and a scope (per user); a crash between side effect and record still leaves a window.

React to database changessenior

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
DebeziumDynamoDB StreamsPostgres logical replication
Watch out

Consumers see row diffs, not domain events; schema changes ripple downstream.

Coordinate a multi-service transactionstaff

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.

Storage & data modelling

Pick the store and the shape of the data for the access pattern.

Flexible, nested recordsfundamental

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
MongoDBCouchbasePostgres JSONB
Watch out

Easy to end up with inconsistent shapes; validate at the edge.

Metrics and events over timesenior

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
InfluxDBTimescaleDBPrometheusClickHouse
Watch out

Cardinality explosion from too many label combinations.

Deep relationship queriessenior

"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
Neo4jNeptuneadjacency lists in Postgres
Watch out

Most "graph" needs (followers, following) are fine as two indexed tables.

Know your write amplificationsenior

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 indexesbatched writestiered vs levelled compactionappend-only logs
Watch out

SSD wear and I/O saturation show up long before CPU does on write-heavy systems.

Know your read amplificationsenior

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 filtersdenormalised read modelssingle-shard access patternsMGET batching
Watch out

Trading read amplification for write amplification is the usual deal; say which side you chose.

Change the schema without downtimesenior

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-ostpt-online-schema-changeFlywayLiquibase
Watch out

Two code versions run at once during a deploy; both must tolerate both schemas.

Consistency & coordination

Agree on one truth across many nodes.

Let users see their own writessenior

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 writeLSN / version tokens in the sessioncausal consistency
Watch out

Only the writer needs this guarantee; other users can tolerate the lag.

Pick consistency or availability under partitionsenior

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.

Make an expired lease harmlessstaff

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 tokensZooKeeper zxidetcd revisionsconditional writes on version
Watch out

The protected resource must check the token; a lock alone cannot stop a zombie writer.

Lock the row before changing itsenior

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 UPDATESKIP LOCKED for job queuesadvisory locks
Watch out

Holding locks across network calls causes deadlocks and timeouts; keep the critical section tiny.

Order events within a streamsenior

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 offsetsper-conversation countersLamport / vector clocks
Watch out

Global ordering across streams is expensive; only order where the product needs it.

Commit across two storesstaff

A single operation must succeed in two databases or neither.

Basic solution

Two-phase commit with a coordinator: prepare on all, then commit on all. Prefer avoiding it via sagas or outbox.

Tools to name
XA transactionsSpannersagas as the alternative
Watch out

Blocks while the coordinator is down; slow; rarely worth it.

Reliability & failure handling

Keep working when parts fail.

Never wait foreverfundamental

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 timeoutsgRPC deadlinescontext cancellation
Watch out

A timeout is not a failure of the remote side; the work may still complete there.

Isolate failuressenior

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 dependencyseparate queuescells
Watch out

Smaller pools mean each partition has less headroom.

Degrade instead of failingfundamental

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 flagsfallback responsesstale-while-revalidate
Watch out

Know which features are critical before the incident, not during.

Admit only what you can finishstaff

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 timeoutsper-tenant quotasdeadline propagation
Watch out

Rejecting early looks worse on a dashboard than queueing, but it keeps the successful requests fast.

Spread across zones and regionsstaff

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 deploymentscross-region replicationRoute 53 failover
Watch out

Active-active across regions needs conflict handling; active-passive needs regular failover drills.

Networking & delivery

Get bytes to clients quickly and safely.

Choose the API stylefundamental

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
RESTgRPCGraphQLOpenAPI
Watch out

gRPC needs HTTP/2 end to end; GraphQL needs query cost limits.

Change an API without breaking clientssenior

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 pathsAccept-Version headerProtobuf field numbering
Watch out

Every live version is code you maintain; publish deprecation dates.

Pick the right redirectfundamental

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
301302307308
Watch out

A cached 301 cannot be undone for returning users.

Put a reverse proxy in frontfundamental

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
nginxEnvoyCaddyTraefik
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.

Push to the browser in real timefundamental

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
WebSocketSocket.IOconnection registry in Redis
Watch out

Stateful connections need sticky routing, a registry, and reconnect-with-cursor logic.

Find which server holds a usersenior

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 TTLRedis Pub/Sub per serverconsistent hashing of users to servers
Watch out

Stale entries after crashes; refresh on heartbeat.

Track online status cheaplysenior

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 TTLbatched heartbeatssubscription lists
Watch out

Typing indicators are transient: never store them.

Find things near a pointsenior

"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 GEOH3S2PostGISquadtrees for static points
Watch out

Boundary effects: always check neighbouring cells; moving points churn tree structures.

Ingest millions of position updatessenior

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 regionRedis GEOadaptive update intervals
Watch out

Last-writer-wins on timestamps; archive history separately.

Deliver to users who are offlinesenior

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 / queuesync cursorssilent push to wake the app
Watch out

Inbox growth for long-offline users; cap and fall back to history reads.

Data processing & search

Compute over large data and find things in it.

Move data between systemssenior

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
AirflowFivetranKafka ConnectDebezium
Watch out

Schema drift and late data; make loads idempotent and replayable.

Rank instead of sorting by timestaff

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 storecandidate generation + scoringlearning-to-rank
Watch out

Keep a chronological fallback; ranking needs offline evaluation and logging.

Suggest as the user typessenior

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
trieElasticsearch completion suggesterRedis sorted sets
Watch out

Fuzzy matching and personalisation multiply the index size.

Security & abuse

Keep out the wrong people and the wrong traffic.

Authenticate, then authorisefundamental

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 / OIDCJWTsession cookiesRBAC / ABACAuth0 / Cognito
Watch out

JWTs cannot be revoked before expiry; keep them short and pair with refresh tokens.

Protect data and secretssenior

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
VaultAWS KMS / Secrets Managerbcrypt / Argon2TLS everywhere
Watch out

Encryption at rest does not protect against an application-level bug.

Validate at the edgefundamental

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 Schemaparameterised SQLrequest size limitsWAF
Watch out

Validate on the server even if the client already did.

Catch spam and abusesenior

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 APIreputation scoresCAPTCHAallow / deny lists
Watch out

False positives hurt real users; keep an appeal path.

Keep the server out of the contentstaff

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 protocolX3DHDouble 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.

Measure what users feelfundamental

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 + GrafanaDatadogthe four golden signalsSLOs / error budgets
Watch out

Averages hide tail latency; alert on p99.

Set SLOs and spend the error budgetsenior

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 / SLOsburn-rate alertserror budget policy
Watch out

Pick SLIs users feel (success rate, latency), not internal ones (CPU).

Log so you can queryfundamental

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 / OpenSearchLokiCloudWatch Logs
Watch out

Never log secrets or full PII; sample noisy debug logs.

Follow one request across servicessenior

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
OpenTelemetryJaegerZipkinHoneycomb
Watch out

Sample traces at scale; make sure queues propagate context too.

Tag every log line with the requestfundamental

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-IDW3C traceparentOpenTelemetry context propagationMDC / structured log fields
Watch out

Async hops drop context unless you put the id in the message envelope.

Ship dark, release graduallyfundamental

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
LaunchDarklyUnleashconfig service
Watch out

Flags accumulate; delete them after rollout.

Deploy without downtimesenior

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 updatescanary analysisArgo RolloutsALB weighted targets
Watch out

Both versions run together; schema and API changes must be backward compatible.

Size the system from numbersfundamental

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 estimatesload testing (k6, Locust)the Estimator page
Watch out

Peak is 3–10× average; design for peak and for one zone being down.