Software Engineering
Design systems that scale and survive failure: trade-offs, data stores, caching, messaging and cloud patterns.
A path through the building blocks of large distributed systems, for backend engineers and anyone preparing for design interviews. It covers the core trade-offs, DNS, CDNs and load balancers, databases and caching, asynchronous work, communication protocols, monitoring, and a catalogue of cloud design patterns. Each subject links official documentation or a primary source.
The subjects follow the roadmap.sh System Design roadmap.
System design is deciding how the pieces of a large software system fit together: services, data stores, caches, queues and the network between them. Every choice trades latency, cost, consistency and operational effort against each other, and the skill is making those trade-offs explicit.
Defining the architecture, components, interfaces and data flow of a system so it meets functional needs plus non-functional ones like scale, availability and security. It works at the level of boxes and arrows, then justifies each box.
Clarify requirements and constraints, estimate load (requests per second, storage, bandwidth), sketch a high-level design, then deep-dive the bottlenecks. State assumptions and the trade-off behind every decision.
Performance is how fast the system serves one user; scalability is whether it keeps that speed as load grows when you add resources. A system can be fast for one request and collapse under a thousand, so you fix them with different tools.
Latency is the time one operation takes; throughput is how many operations complete per unit of time. Aim for maximal throughput at acceptable latency, and track latency as percentiles (p50, p99) rather than averages, since tail latency is what users feel.
In a distributed system, network partitions will happen, and during one you must choose between answering every request and guaranteeing every answer is current. The choice is usually made per feature, not per company.
A distributed store can guarantee at most two of consistency, availability and partition tolerance. Since partitions cannot be ruled out, the real choice is C or A while partitioned; PACELC extends it to latency versus consistency in normal operation.
During a partition, the minority side refuses or times out requests rather than return stale data. Right for balances, inventory and locks; systems built on consensus such as etcd and ZooKeeper behave this way.
Every node keeps answering during a partition, possibly with stale data, and replicas reconcile afterwards. Suits feeds, carts and counters where a slightly old answer beats an error.
When data lives on several replicas, the consistency model defines what a read may return after a write. Stronger models are easier to reason about but cost latency and availability.
After a write, reads may or may not see it, with no guarantee of when. Fine for live video, game state or VoIP, where a lost update is replaced by the next one anyway.
If writes stop, all replicas converge to the same value, usually within milliseconds. Reads can be stale meanwhile, so design for it with read-your-writes tricks or conflict resolution such as last-write-wins or CRDTs.
Every read sees the latest committed write, as if there were one copy. Achieved with synchronous replication or consensus (Raft, Paxos), at the cost of write latency and availability during partitions.
Availability comes from redundancy: more than one copy of every component and a way to switch between them. The two building blocks are fail-over for stateless and stateful nodes, and replication for data.
Switching traffic to a standby when the primary fails, driven by health checks or heartbeats. It adds hardware and complexity, and a fail-over that has never been tested will probably fail when you need it.
One node serves traffic while a standby waits, taking over the IP or DNS name when heartbeats stop. Hot standbys switch in seconds; cold ones need to boot and warm up first.
All nodes serve traffic and share load, so losing one just reduces capacity. Needs a load balancer or DNS in front, and stateful nodes need a strategy for conflicting writes.
Keeping copies of data on several nodes for availability and read scaling. Synchronous replication never loses acknowledged writes but adds latency; asynchronous is faster but can lose recent writes on fail-over.
Now usually called primary-replica: one node takes writes and streams them to read-only replicas. Simple and common, but the primary is a write bottleneck and promoting a replica needs care to avoid data loss.
Several nodes accept writes and replicate to each other. Gives write availability across regions but needs conflict resolution, and writes can be lost or reordered under loose consistency.
Availability is uptime divided by total time, usually stated as "nines". Each extra nine cuts allowed downtime tenfold, and it is cheaper to define an honest SLO than to chase nines nobody needs.
About 8 hours 46 minutes of downtime per year, or roughly 43 minutes per month. Achievable with redundancy in one region and decent on-call.
About 52 minutes per year, or 4.3 minutes per month. Humans cannot react that fast, so it needs automated fail-over, multi-zone redundancy and careful deploys.
Components in sequence multiply availabilities, so two 99.9% services in a chain give about 99.8%. Redundant components in parallel give 1 minus the product of their failure rates, so two 99.9% replicas reach about 99.9999%.
Work that does not need to finish inside the request, such as emails, image processing, reports and syncs, runs in separate workers. That keeps responses fast and lets heavy work retry and scale on its own, but jobs must be idempotent because they will run twice eventually.
Jobs triggered by something happening: a message on a queue, a file upload, a database change. Workers react as events arrive and scale with queue depth.
Jobs triggered by time, such as a nightly cleanup via cron or a scheduler. Guard against overlapping runs and against several instances firing the same schedule.
The caller needs to learn the outcome: poll a status endpoint, receive a webhook or callback, read a result from a reply queue, or get a push over WebSocket.
DNS turns names into IP addresses through a hierarchy of resolvers and authoritative servers, with answers cached for each record's TTL. Beyond lookups it is a traffic tool: weighted, latency-based and geo routing all happen at DNS, but low TTLs are not always honoured, so fail-over through DNS is slow.
A CDN is a global network of edge servers that serves content from close to the user, cutting latency and offloading the origin. Mostly used for static assets, but modern CDNs also cache API responses and run code at the edge.
You upload content to the CDN yourself whenever it changes. Good for sites with little traffic or content that rarely changes, since nothing expires unexpectedly, but you manage storage and invalidation.
The edge fetches from your origin on the first request and caches it for the TTL. Easy to run and suits high-traffic sites; the first visitor per edge pays the miss, and Cache-Control headers decide freshness.
A load balancer spreads requests across healthy backends, removes failed ones via health checks, and often terminates TLS. Run at least two, since the balancer itself is otherwise a single point of failure.
A reverse proxy sits in front of servers to add TLS, compression, caching and a single public face, and is useful even with one backend. A load balancer is a reverse proxy whose main job is spreading traffic across many backends.
Round robin and weighted round robin, least connections, least response time, IP or consistent hashing for stickiness, and random with two choices. Least-connections handles uneven request costs better than round robin.
Routes on HTTP details such as path, host, headers and cookies, so /api and /video can go to different pools. Costs more CPU than layer 4 because it must parse and often decrypt traffic.
Routes on IP addresses and ports without looking at the payload, forwarding TCP or UDP connections. Very fast and protocol-agnostic, but cannot make content-aware decisions.
Adding more machines instead of bigger ones. It needs stateless application servers, with sessions and files moved to shared stores, and brings the complexity of a distributed system.
Separating the web tier from the application tier lets each scale and deploy independently. Taken further, the application layer splits into independently deployable services that find each other dynamically.
Small services, each owning its data and deployed independently, talking over the network. They buy team autonomy and independent scaling at the cost of distributed failures, data consistency problems and operational overhead.
How a service finds healthy instances of another when addresses change constantly: a registry like Consul or etcd, DNS-based discovery, or Kubernetes Services, which give a stable virtual IP and DNS name.
The data store is usually the hardest part of a system to scale and change. Choose by access pattern, consistency needs and how the data relates, then plan how it grows beyond one machine.
Relational databases give schemas, joins and transactions; NoSQL stores trade some of that for flexible models and easier horizontal scaling. Default to SQL unless the access pattern clearly fits a NoSQL model.
Relational databases store rows in tables with ACID transactions. Scaling them means replication for reads, then splitting data by function or by key, with denormalization and query tuning along the way.
Splitting databases by function, such as users, products and orders, so each has less traffic and fits in memory better. Cross-database joins move into the application.
Partitioning rows across databases by a shard key, so each holds a subset. Choose the key to avoid hot spots; cross-shard queries and resharding are the hard parts.
Storing redundant copies of data to avoid expensive joins, trading write complexity for read speed. Materialized views can keep the copies in sync for you.
Read query plans with EXPLAIN, add the right indexes, avoid SELECT * and N+1 queries, use connection pooling, and benchmark with realistic data before and after.
Non-relational stores built around one data model and usually designed to scale out. Most favour availability and partition tolerance, and you design the schema from the queries rather than from the entities.
A hash map at scale: get and put by key in constant time. Ideal for caches, sessions and simple lookups; Redis and DynamoDB are typical.
Stores JSON-like documents that can be queried by their fields. Good when data is naturally nested and read whole; MongoDB is the common example.
Rows keyed by partition and clustering keys, holding sparse columns, built for huge write volumes across many nodes. Cassandra and HBase are examples; queries must follow the key design.
Nodes and edges as first-class data, so traversals such as friends of friends or fraud rings are fast without join chains. Neo4j with Cypher is the best known.
A cache keeps hot data closer and faster than its source, cutting latency and database load. The hard parts are invalidation, choosing TTLs, and avoiding stampedes when a popular key expires.
Browsers and apps cache responses locally, controlled by Cache-Control, ETag and Last-Modified. The fastest request is the one never sent.
Edge servers cache static assets and cacheable responses near users. Use versioned file names for assets and s-maxage for shared caches.
Reverse proxies such as NGINX or Varnish cache whole responses so the application never sees repeated requests.
Databases keep hot pages and plans in memory (buffer pool, shared buffers). Sizing that memory well is often the cheapest speed-up available.
An in-memory store such as Redis or Memcached between the app and database. Cache objects or query results, set TTLs, and pick an eviction policy like LRU.
The app reads the cache, falls back to the database on a miss and writes the result into the cache. Only requested data is cached, but each miss costs three trips and data can go stale until the TTL.
Writes go to the cache, which synchronously writes to the database. Reads are always fresh, but writes get slower and the cache fills with data nobody reads.
Writes land in the cache and are flushed to the database asynchronously, giving fast writes. Data is lost if the cache dies before flushing, so it suits counters more than payments.
The cache refreshes hot entries shortly before they expire, so readers rarely see a miss. Works when you can predict which keys will be needed; wrong guesses waste work.
Moving work out of the request path smooths spikes and lets slow tasks run in the background. The cost is eventual consistency and the need to handle duplicates, ordering and failures explicitly.
Brokers such as RabbitMQ, SQS or Kafka store messages until consumers process them, decoupling producers from consumers. Expect at-least-once delivery and design consumers to be idempotent.
Queues of jobs with arguments, picked up by worker processes that run code, with retries and scheduling built in. Celery, Sidekiq and BullMQ are common choices.
When a queue grows faster than it drains, slow the producers down: bound the queue, reject with HTTP 503 or 429 and a retry hint, and let clients back off. Unbounded queues only hide overload until memory runs out.
How services and clients talk shapes latency, coupling and failure behaviour. Pick the transport (TCP or UDP), then the application protocol and API style that fit who is calling and how.
The request/response protocol of the web: methods, status codes, headers and caching semantics. HTTP/2 multiplexes streams over one connection; HTTP/3 runs over QUIC on UDP.
Connection-oriented transport with ordered, reliable delivery, flow control and congestion control. The handshake and head-of-line blocking add latency, which is why connection reuse matters.
Connectionless datagrams with no delivery or ordering guarantees and minimal overhead. Used for DNS, real-time media, games and as the base for QUIC.
Calling a function on another machine as if it were local. Convenient, but the network is not local: plan for timeouts, retries and partial failure, and avoid chatty fine-grained calls.
An architectural style of resources addressed by URLs and manipulated with standard HTTP methods, statelessly. Easy to cache and understand; can need several round trips for one screen.
RPC framework using Protocol Buffers over HTTP/2, with generated clients, streaming in both directions and deadlines. Great between services; browsers need gRPC-Web or a gateway.
A typed query language where the client asks for exactly the fields it needs in one request. Watch for N+1 resolvers (use DataLoader), query cost limits and harder HTTP caching.
An idempotent operation has the same effect whether it runs once or many times. Since retries, redelivered messages and double clicks are unavoidable, make writes idempotent with natural keys, upserts or a client-supplied idempotency key the server remembers.
Common designs that work in testing and fall over under real load. Knowing them by name makes them easier to spot in reviews and incident analyses.
Putting heavy processing such as formatting or business logic in stored procedures, so the shared database becomes the bottleneck. Move compute to scalable app servers.
Doing long, resource-heavy work on the threads that serve requests, which starves every other user. Offload it to background workers.
Many small network or disk calls where one batched call would do, such as an N+1 query loop. Each call pays full latency, so batch, join or aggregate.
Retrieving more data than needed, like whole tables filtered in memory or every column when two are used. Push filtering, projection and pagination to the store.
Creating clients meant to be shared, such as HTTP clients or DB connections, per request. That exhausts sockets and adds setup cost; create them once and reuse them.
One data store for every kind of data, so logs, sessions and transactions compete for the same resources. Pick stores per workload.
Fetching the same rarely changing data from the source on every request. Add a cache with a sensible TTL and invalidation path.
One tenant hogs shared resources and degrades everyone else in a multi-tenant system. Apply per-tenant quotas, throttling or isolation.
Clients retrying immediately and endlessly against a struggling service, keeping it down. Use capped exponential backoff with jitter, retry budgets and circuit breakers.
Blocking a thread while waiting for I/O, so throughput is capped by thread count. Use async I/O so threads serve other work while waiting.
You cannot run what you cannot see. Collect metrics, logs and traces, watch the golden signals (latency, traffic, errors, saturation), and alert on symptoms users feel rather than on every internal blip.
A fast, current view of whether each component is healthy, built from liveness checks, error rates and dependency status, usually rolled up into a dashboard.
Measures uptime from the user's side with synthetic probes from several regions and success rates, tracked against SLOs and error budgets.
Latency percentiles, throughput and resource saturation over time, so you see degradation before it becomes an outage and can plan capacity.
Watching for suspicious activity: failed logins, unusual access patterns, privilege changes. Feed audit logs into a SIEM and alert on anomalies.
How features and resources are actually used: active users, popular endpoints, per-tenant consumption. Drives billing, capacity planning and product decisions.
Adding the code that emits metrics, structured logs and traces. OpenTelemetry gives vendor-neutral APIs and propagates trace context across services.
Dashboards that answer "is it broken and where", and alerts that page a human only for actionable, user-facing problems. Every alert should have a runbook.
Named, reusable solutions to recurring problems in distributed cloud systems: messaging, data, structure, reliability and security. The catalogue below follows the widely used Azure Architecture Center set, but the patterns apply on any cloud.
Patterns for connecting components through messages so they scale and fail independently. They deal with ordering, load spikes, large payloads and coordinating multi-step work.
Process related messages in order, such as all events for one order, while unrelated groups still run in parallel. Usually done with sessions or partition keys.
A scheduler drives the steps of a distributed workflow, agents call the remote services, and a supervisor watches for stuck or failed steps and retries or compensates them.
Put a queue between callers and a service so bursts are absorbed and the service drains at its own pace. Protects downstream systems from spikes at the cost of latency.
Publishers emit events to a topic without knowing who listens; each subscriber gets its own copy. Decouples senders from receivers and makes adding consumers cheap.
Process urgent requests before others, either with a queue that orders by priority or with separate queues and more consumers for the important one.
Break processing into independent stages connected by queues, so each stage can scale, be reused and be replaced on its own.
Several workers pull from the same queue, each message going to one of them. Scales throughput and survives worker failure; messages must be safe to process twice.
Services react to each other's events instead of a central orchestrator telling them what to do. Less coupling, but the overall flow becomes harder to see and debug.
Store a large payload in blob storage and send only a reference through the message bus, keeping messages small and cheap.
For long-running work, return 202 Accepted with a status URL right away, let the client poll it, and redirect to the result when done.
Patterns for storing, shaping and serving data across distributed stores, where joins and transactions spanning everything are no longer available.
Serve static files straight from object storage or a CDN instead of app servers, cutting cost and freeing compute for dynamic work.
Precompute read-optimised views of data that is stored in a write-friendly shape, and refresh them when the source changes.
Build your own secondary index tables in stores that lack them, mapping a query field to the primary keys of matching items.
Store every change as an append-only event and derive current state by replaying them. Gives a full audit trail and time travel, at the cost of schema evolution and projection complexity.
Separate the model that handles writes (commands) from the one that serves reads (queries), so each can be optimised and scaled independently. Worth it only where reads and writes differ a lot.
Structural patterns for how services are composed, deployed and evolved, from edge gateways to helpers that run beside each service.
Replace a legacy system gradually by routing features one at a time to new code behind a facade, until the old system can be switched off.
Run supporting features such as logging, proxies or config watchers in a separate process or container next to the app, sharing its lifecycle. Service meshes are built on this.
Among identical instances, elect one to coordinate shared work, using a lease or lock in a consistent store, and re-elect when it dies.
One endpoint routes requests to the right backend by path or header, so clients do not need to know the service layout.
Move shared concerns such as TLS termination, authentication and rate limiting into the gateway instead of every service.
The gateway fans one client request out to several services and combines the answers, saving the client round trips.
Keep configuration in a central store outside the deployment package, so settings can change without redeploying and be shared across services.
Pack several small tasks or components into one compute unit to raise utilisation and cut cost, as long as they scale and fail similarly.
A separate backend per client type (web, mobile, partner) shaped to its exact needs, owned by the team building that client.
A translation layer between your model and a legacy or external system, so its concepts and quirks do not leak into your design.
An out-of-process proxy that handles outbound connectivity for a service, such as retries, monitoring and TLS, useful for legacy apps you cannot change.
Patterns that keep a system up and correct when parts of it fail: spreading load, isolating faults, recovering automatically and controlling who can reach what. They are grouped below into availability, high availability, resiliency and security.
Keeping the service reachable and responsive under load. The main tool beyond redundancy is controlling how much work gets in.
Limit how many resources a client or tenant can use, rejecting or degrading excess requests with 429, so the service stays up for everyone during spikes.
Designs that survive whole zones or regions failing, by deploying independent copies and detecting failure quickly.
Deploy many independent copies (stamps or cells) of the whole stack, each serving a subset of tenants, so a failure or bad deploy affects only one cell.
Deploy identical backends in many regions, each able to serve any user, behind global routing, giving low latency and survival of regional outages.
Expose endpoints like /health that check the app and its critical dependencies, so load balancers and monitors can pull unhealthy instances out.
Isolate resources such as thread pools and connection pools per dependency or tenant, so one failing part cannot drain resources from the rest.
After repeated failures, stop calling a dependency for a while and fail fast, then let a trial request through to test recovery. Prevents cascading failure and gives the dependency room to recover.
Recovering from failures without human help, and undoing partial work when a multi-step operation cannot finish.
Retry transient failures with exponential backoff and jitter, a cap on attempts, and only for idempotent operations or with idempotency keys.
When one step of an eventually consistent workflow fails, run steps that undo the earlier ones, such as cancelling a booking. This is the core of the saga pattern.
Patterns that control who can reach which resource, with as little exposure and as few long-lived secrets as possible.
Delegate authentication to an external identity provider via OpenID Connect or SAML, so apps never handle passwords and users get single sign-on.
A hardened front host validates and sanitises requests before passing them to trusted services that never face the internet directly.
Give clients a short-lived, narrowly scoped token, such as a pre-signed URL, to read or write storage directly, so large uploads skip your servers.