Scaling
Increase throughput by adding resources to one node (vertical) or adding identical nodes behind a load balancer (horizontal).
Vertical scaling adds CPU, memory, or IOPS to a single node. It needs no application changes and keeps consistency trivial because there is exactly one copy of state. The limits are a hard ceiling set by the largest available instance, cost that grows faster than capacity near the top, a restart to resize, and a node that remains a single point of failure.
Horizontal scaling runs N identical replicas behind a load balancer. Throughput grows roughly linearly as long as replicas are stateless and the shared dependencies (database, cache, third-party APIs) can absorb the extra connections. In production the replica count is driven by autoscaling and sized against p99 latency targets, not averages.
Production checklist
- Externalize state: sessions in Redis or signed tokens, files in object storage, nothing on local disk that must survive a restart.
- Budget connections. 50 pods with a pool of 20 each is 1,000 Postgres connections; put a pooler such as PgBouncer in front of the database.
- Start fast and shut down gracefully so scale-in and deploys don't drop in-flight requests (see connection draining).
- Run N+1 across availability zones: losing one zone must leave enough capacity to serve peak traffic.
- Load-test to find the first bottleneck before production does. It is usually the database, not the app tier.
You get
- Vertical: no code changes, single-node transactions, simplest operations
- Horizontal: near-linear throughput, zone-level fault tolerance, rolling deploys
You pay
- Vertical: hard ceiling, single point of failure, downtime to resize
- Horizontal: stateless design, a load-balancing tier, connection fan-out to shared stores, distributed debugging
Rule of thumbScale vertically while it's cheap, but ship stateless services from day one so horizontal scaling is an autoscaler setting, not a migration.
Load balancing
Distributes traffic across a pool of backends and removes unhealthy ones from rotation.
A load balancer accepts client connections and forwards each request or connection to a backend chosen by an algorithm. Its most important job is failure isolation. Active health checks probe every backend on an interval (for example every 5 s, unhealthy after 3 failures, healthy again after 2 successes), and passive checks, called outlier detection in Envoy, eject backends that start returning 5xx responses. Try it: take App B down in the live diagram on the home page.
Layer 4 vs layer 7
L4 balancers (AWS NLB, Linux IPVS, Google Maglev) forward TCP or UDP flows by their 5-tuple without parsing the payload. They handle millions of connections with microsecond overhead and can preserve the client IP. L7 balancers (AWS ALB, Envoy, NGINX, HAProxy) parse HTTP, which enables path and header routing, TLS termination, per-request retries and timeouts, and HTTP/2 or gRPC multiplexing.
One common production trap: an L4 balancer spreads connections, not requests. gRPC and HTTP/2 clients hold one long-lived connection, so every request lands on the same backend. Use an L7 balancer or client-side balancing for those protocols.
| Algorithm | How it picks | Use when |
|---|---|---|
| Round robin | Next backend in order | Homogeneous backends, uniform request cost |
| Weighted round robin | Proportional to configured weight | Mixed instance sizes, canary releases (e.g. 5% weight) |
| Least request (P2C) | Samples two random backends, picks the one with fewer active requests | Variable request cost; Envoy's default least-request mode |
| Ring hash / Maglev | Hash of a key (header, cookie, IP) selects a backend | Session affinity or per-key local caches; see virtual nodes |
Production checklist
- Separate readiness from liveness. Readiness fails when the instance can't serve; liveness fails only when the process is wedged and must be restarted.
- Enable connection draining (typically 30 to 60 s) so deploys don't reset in-flight requests.
- Set a timeout at every hop, each shorter than its caller's, and cap retries with a retry budget so a slow backend doesn't trigger a retry storm.
- Make the balancer itself redundant: managed balancers span zones; self-hosted pairs use VRRP (keepalived) or anycast.
You get
- Automatic failover and ejection of bad backends
- Zero-downtime deploys via draining
- One stable endpoint, central TLS and routing policy
You pay
- An extra network hop (sub-millisecond within a zone)
- Another tier that must be highly available
- A misconfigured health check can eject every backend at once
Rule of thumbThe health check is the product. Make readiness reflect whether an instance can actually serve, and never let one shared dependency fail every instance's liveness at the same time.
Caching
Serve repeated reads from a faster tier to cut latency and offload the source of truth.
An in-process memory lookup costs about 100 ns, a Redis round trip in the same zone roughly 0.2 to 0.5 ms, and an indexed Postgres query typically 1 to 10 ms. A cache with a 95% hit ratio reduces read load on the database by 20×. Caching happens at every layer: the browser (Cache-Control), the CDN, the application (Redis, Memcached), and the database's own buffer pool.
Write strategies
- Cache-aside (lazy loading): read the cache; on a miss, read the database and
SETthe value with a TTL. On writes, update the database, thenDELthe key. Deleting beats updating because two racing writers can't leave an older value behind. - Write-through: write the cache and the database in the same code path. Reads are fresh, writes are slower, and you may cache data nobody reads.
- Write-back (write-behind): acknowledge after writing the cache and flush to the database asynchronously. Lowest write latency, but data is lost if the cache fails before flushing.
Failure modes
- Cache stampede: a hot key expires and thousands of concurrent misses hit the database at once. Mitigate with request coalescing, TTL jitter, or early probabilistic refresh.
- Stale reads: bounded by the TTL, so a missed invalidation heals itself when the entry expires.
- Eviction: set
maxmemoryand an eviction policy such as LRU or LFU. Without a policy, Redis rejects writes once memory is full. - Cold start: an empty cache sends 100% of reads to the database. Warm critical keys before cutover and size the database to survive it.
You get
- An order of magnitude lower read latency
- Large reduction in database read load and cost
You pay
- Reads can be stale up to the TTL
- Another stateful system to operate, monitor, and fail over
- Invalidation logic spread across write paths
Rule of thumbCache data that is read far more often than it changes, always set a TTL with jitter, and size the database to survive a cold cache.
Replication & sharding
Replication copies the same data to multiple nodes; sharding partitions different data across nodes.
In leader-follower replication the leader records every change in its write-ahead log and streams it to followers. Asynchronous replication gives the lowest write latency, but a failover can lose writes that hadn't shipped yet. Synchronous or semi-synchronous replication waits for at least one follower to acknowledge, trading write latency for durability. Followers serve reads, so read throughput scales with the number of replicas, subject to replication lag. To guarantee read-your-writes, route a user's reads to the leader for a short window after they write.
Leaderless replication (Dynamo-style stores such as Cassandra) writes to N replicas and uses a quorum: with W + R > N, every read overlaps at least one replica that holds the latest write.
Sharding partitions the keyspace once write throughput or dataset size exceeds what one leader can handle. Range partitioning keeps ordered scans efficient but concentrates sequential keys, such as timestamps, on one shard. Hash partitioning spreads load evenly but gives up range queries. The shard key should appear in nearly every query so each request touches a single shard; everything else becomes a scatter-gather across all of them.
Production checklist
- Automate failover with fencing to prevent split-brain, using Patroni, Orchestrator, or a managed service such as RDS Multi-AZ or Aurora.
- Alert on replication lag in both seconds and bytes, and stop routing reads to a follower that exceeds your staleness budget.
- Pre-split into many logical shards (for example 1,024) mapped onto fewer physical nodes, so rebalancing moves whole shards instead of individual rows.
- Plan for hot keys: one very active tenant or celebrity account can saturate a single shard regardless of how many you have.
You get
- Replication: read scaling, high availability, backups and analytics without touching the leader
- Sharding: write throughput and storage beyond a single machine
You pay
- Replication: lag, stale reads, and failover edge cases
- Sharding: no cheap cross-shard joins or transactions, complex resharding, hot partitions
Rule of thumbReplicate for availability from day one. Shard only when vertical scaling and read replicas can no longer absorb the write load, and choose the shard key from your query patterns rather than your schema.
CAP & consistency
During a network partition, a replicated system must either reject requests or serve data that may be stale.
CAP is often summarized as "pick two of three," which is misleading. Network partitions are not optional in real deployments, so the trade-off only bites while one is happening: a node that can't reach a quorum must either refuse the operation (CP) or answer with data that may be stale or conflicting (AP). When the network is healthy, a well-designed system provides both consistency and availability.
PACELC: the everyday trade-off
PACELC extends CAP: if Partitioned, choose Availability or Consistency; Else, choose Latency or Consistency. The second half matters more often. Linearizable writes across regions require a cross-region round trip, commonly 50 to 200 ms, on every write.
Consistency models, strongest to weakest
- Linearizable: each operation appears to take effect atomically at one point between its start and end. Required for locks, leader election, and uniqueness guarantees.
- Causal: operations that are causally related are seen in the same order by every node; concurrent ones may differ.
- Session guarantees: read-your-writes and monotonic reads. Often sufficient for user-facing apps.
- Eventual: replicas converge once writes stop; conflicts are resolved by last-write-wins, version vectors, or CRDTs.
| System | Default | Tunable |
|---|---|---|
| PostgreSQL (single leader) | Linearizable on the primary; async replicas serve possibly stale reads | synchronous_commit, synchronous_standby_names |
| MongoDB | Reads from primary; write concern majority by default since 5.0 | readConcern, readPreference |
| DynamoDB | Eventually consistent reads | ConsistentRead=true per request (same region) |
| Cassandra | Consistency level chosen per query | ONE, LOCAL_QUORUM, QUORUM, ALL |
| etcd | Linearizable reads and writes via Raft (CP) | Serializable reads trade freshness for latency |
Rule of thumbChoose consistency per operation, not per system. Balances, inventory reservations, and idempotency keys need linearizable writes; feeds, counters, and analytics tolerate eventual consistency.
Consistent hashing
Maps keys to nodes so that adding or removing a node relocates only about 1/N of the keys.
With modulo placement, hash(key) % N, changing N from 4 to 5 remaps about 80% of all keys. For a cache cluster, that's a near-total miss storm the moment you scale. Consistent hashing places nodes and keys on the same hash space, a ring of 232 or 264 positions. A key belongs to the first node clockwise from its position, so adding a node only takes over the arc between it and its predecessor.
With a single position per node, arc sizes vary widely and one node can own several times its fair share. Production implementations give each node 100 to 256 virtual nodes, which evens out load and lets larger machines take proportionally more by weight. Replication fits naturally: store each key on the next R distinct physical nodes clockwise.
Squares are servers, circles are keys. Keys with a thick outline just changed owner.
Alternatives
Jump consistent hash needs no ring in memory and balances almost perfectly, but buckets can only be added or removed at the end. Rendezvous (highest random weight) hashing scores every node per key and picks the highest, which is simple and even but costs O(N) per lookup. Maglev hashing builds a fixed lookup table for very fast, stable load balancing. You'll find these in Cassandra and DynamoDB partitioning, Envoy's ring_hash and maglev balancers, and memcached client libraries.
You get
- Minimal data movement when nodes join or leave
- No central lookup service on the request path
- Natural placement for replicas
You pay
- Uneven load without virtual nodes
- Hot keys still overload one owner
- Membership changes must propagate consistently to every client
Rule of thumbWhenever a key-to-node mapping must survive nodes joining and leaving (caches, partitioned stores, sticky load balancing), use consistent hashing with virtual nodes.
Message queues
Buffer work between producers and consumers so each side can scale and fail independently.
Producers enqueue a message and return immediately; consumers pull at their own rate. This decouples availability (the email service can be down for ten minutes without losing a single signup), absorbs traffic bursts, and gives every task the same retry path. Queue depth and the age of the oldest message are the primary signals for scaling consumers.
Delivery semantics
Most brokers provide at-least-once delivery. SQS hides a received message for a visibility timeout and redelivers it if the consumer doesn't delete it in time. Kafka redelivers everything after the last committed offset when a consumer restarts. Exactly-once effects therefore require idempotent consumers that deduplicate on a message ID inside the same transaction as the side effect. Messages that keep failing move to a dead-letter queue after a maximum receive count.
Queue vs log
A queue (SQS, RabbitMQ) deletes each message once it's acknowledged and supports per-message visibility and redelivery. A log (Kafka, Kinesis) retains messages for a configured period, orders them within a partition, supports replay, and lets many consumer groups read independently. Consumer parallelism in a log is capped by the partition count.
Production checklist
- Publish from the same database transaction as the state change using the outbox pattern, avoiding dual-write inconsistencies.
- Apply backpressure: bounded queues, consumer concurrency limits, and autoscaling on the age of the oldest message.
- Retry with exponential backoff and jitter, and alert as soon as the dead-letter queue is non-empty.
- Choose the partition key for ordering (for example
order_id); ordering is guaranteed only within a partition.
You get
- Temporal decoupling and burst absorption
- Independent scaling of producers and consumers
- Uniform retries and failure isolation
You pay
- Duplicates and reordering to design for
- Eventual rather than immediate results
- A broker to operate, plus lag and DLQ monitoring
Rule of thumbAssume every message arrives at least twice and some arrive out of order. Give every message a unique ID and make every consumer idempotent before an incident forces you to.
Rate limiting
Bounds the request rate per client to protect capacity, enforce fairness, and contain abuse.
Limits are enforced per identity (API key, user ID, or tenant, falling back to IP address) at the edge or API gateway. Over-limit requests get 429 Too Many Requests with a Retry-After header and remaining-quota headers so well-behaved clients can slow down before they're rejected.
The token bucket is the most widely deployed algorithm. A bucket holds up to b tokens and refills at r tokens per second; each request consumes one. Clients can burst up to b requests while the long-run average stays at r. Try it below with b = 5 and r = 1/s.
5 of 5 tokens
| Algorithm | Implementation | Trade-off |
|---|---|---|
| Fixed window | INCR a per-window key with EXPIRE | Allows up to 2× the limit across a window boundary |
| Sliding window log | Sorted set of request timestamps per client | Exact, but memory grows with request count |
| Sliding window counter | Weighted blend of current and previous window counts | Approximate, constant memory; a common production choice |
| Token bucket | Token count plus last-refill timestamp | Allows controlled bursts; two parameters to tune |
| Leaky bucket | Bounded queue drained at a fixed rate | Smooth output, but adds latency under load |
Production checklist
- Across a fleet, keep counters in a shared store and run check-and-decrement atomically, for example as a Redis Lua script.
- Decide in advance whether to fail open or closed when the limiter's store is unavailable. Most public APIs fail open to preserve availability.
- Layer limits: per tenant globally, tighter per endpoint for expensive routes, and a concurrency cap for slow operations.
- Document the limits and expect clients to honor
Retry-Afterwith exponential backoff and jitter.
You get
- Protection from overload and noisy neighbours
- Predictable capacity planning and cost
- A first line of defense against abuse
You pay
- Legitimate traffic spikes get rejected
- Shared counter store on the hot path
- Limits to tune and communicate to clients
Rule of thumbLimit by the identity that matters (API key, user, or tenant, not only IP), apply it atomically, and always tell the client exactly when it can retry.
CDNs & edge caching
Serve content from a location near each user, so most requests never travel to your origin.
A content delivery network runs caches in hundreds of points of presence (PoPs). Anycast or DNS steering sends each user to a nearby PoP, which cuts the round trip from 150 to 250 ms across continents to typically 10 to 30 ms. On a hit, the edge answers directly. On a miss, it fetches from the origin, stores the response, and serves the next user from the edge. TLS terminates at the edge too, so the handshake round trips happen over the short hop.
The origin controls what may be cached through response headers. Cache-Control: public, max-age=60, s-maxage=600 lets browsers keep a response for a minute and shared caches for ten. The cache key decides which requests share a stored object: by default the scheme, host, path, and query string. Every header added to the key through Vary multiplies the number of variants and lowers the hit ratio.
Invalidation
- Expiry: the simplest option. Content is stale for at most the TTL, and no invalidation code is needed.
- Purge: remove objects from every PoP before they expire, by URL or by surrogate key. Tagging responses with the entities they render lets one API call invalidate every page that shows product 42.
- Versioned URLs: fingerprint static assets (
app.3f9a2c.js) and cache them for a year withimmutable. A deploy changes the URL instead of purging anything.
Production checklist
- Enable an origin shield so a global miss costs one origin request, not one per PoP.
- Send stale-while-revalidate and
stale-if-errorso the edge keeps serving while it refreshes, and while the origin is down. - Strip tracking parameters (
utm_*,fbclid) from the cache key, and normalize headers before they reachVary. - Never cache responses that set cookies or contain per-user data. Mark them
privateorno-storeand test it: a cache-key mistake can serve one user's page to another. - Monitor hit ratio by requests and by bytes, plus origin egress. A sudden drop usually means a cache-key change or a purge storm.
You get
- Low latency for users everywhere
- Large reductions in origin load and egress cost
- Capacity to absorb traffic spikes and volumetric DDoS
You pay
- Stale content and purge logic to reason about
- Cache-key mistakes that leak private data or crater the hit ratio
- Another layer to debug: which PoP, which version, which headers
Rule of thumbFingerprint static assets and cache them forever, give dynamic responses a short s-maxage with stale-while-revalidate, and treat the cache key as a security boundary.
Consensus with Raft
A cluster agrees on one ordered log, so every replica applies the same commands in the same order, even while nodes crash.
Consensus is what makes a replicated state machine safe. A cluster of 2f + 1 nodes tolerates f failures: three nodes survive one, five survive two. Every decision needs a majority quorum, and because any two majorities overlap, two leaders can never commit conflicting entries. etcd (and therefore Kubernetes), Consul, CockroachDB, TiKV, and Kafka's KRaft controller all use Raft.
Leader election. Every node starts as a follower. If it hears no heartbeat within its randomized election timeout, it becomes a candidate, increments the term, and asks the others for votes. A node grants at most one vote per term, and only to a candidate whose log is at least as up to date as its own. The first candidate to collect a majority becomes leader and starts sending heartbeats.
Log replication. Clients send writes to the leader, which appends each command to its log and replicates it with AppendEntries. Once a majority has stored an entry, it is committed: the leader advances its commit index, applies the entry, and answers the client. Followers learn the new commit index on the next message and apply the entry too.
Details that matter in production
- Reads: a leader cut off by a partition may not know it has been replaced. For linearizable reads, etcd confirms leadership with a heartbeat round before answering (ReadIndex). Leader leases skip that round but depend on bounded clock drift.
- Membership changes add or remove one voter at a time, or use joint consensus, so two disjoint majorities can never exist mid-change.
- Snapshots replace old log entries, so restarted nodes and new followers don't replay the entire history.
Production checklist
- Run three or five voters spread across zones. Four nodes tolerate no more failures than three, and more voters make every write slower.
- Give the log fast disks. Every commit waits for an fsync on a majority, and etcd's guidance is to keep WAL fsync p99 under 10 ms.
- Use consensus for coordination data (leader election, configuration, locks, shard maps), not bulk data. Systems that need consensus at scale run one Raft group per shard.
- Pass the term or revision to anything the leader writes outside the cluster, as a fencing token that prevents split-brain.
You get
- Linearizable, fault-tolerant state with automatic failover
- No split-brain by construction
- Mature, heavily tested implementations
You pay
- Every write waits for a majority round trip and fsync
- The minority side of a partition can't make progress (CP)
- Throughput limited by one leader per group
Rule of thumbDon't implement Raft yourself. Use etcd, Consul, or ZooKeeper for coordination, run an odd number of voters across zones, and keep the data in them small.
Idempotency & retries
Retries turn transient failures into successes, but only when repeating an operation is safe and the retries can't overload the system.
A remote call can fail in three ways: the request never arrived, it was processed but the response was lost, or it's still running when the caller gives up. The caller can't tell which happened, so the only safe way to retry is to make the operation idempotent. GET, PUT, and DELETE are idempotent by HTTP semantics; POST is not, which is why payment APIs such as Stripe accept an idempotency key on every POST.
Retries need three limits: a deadline for the whole call, exponential backoff with jitter between attempts, and a cap on how much extra load retries may add. Without the cap, a partial outage becomes a retry storm. A circuit breaker goes one step further: after repeated failures it stops calling the dependency for a cool-down period, so callers fail fast and the dependency gets room to recover.
What to retry
| Failure | Retry? | Why |
|---|---|---|
| Connection refused, DNS failure | Yes | The request never reached the server |
| Timeout, connection reset mid-request | Only if idempotent | It may already have been processed |
429, 503 with Retry-After | Yes, after the stated delay | The server is asking you to slow down |
| 500, 502, 504 | Only if idempotent, with backoff | Often transient, sometimes partially applied |
| 400, 401, 403, 404, 409, 422 | No | Retrying won't change the answer |
Production checklist
- Generate the idempotency key on the client once per logical operation and reuse it on every retry. A new key per attempt defeats the purpose.
- Store the key with a hash of the request and the response, reject a reused key that arrives with a different body, and keep keys for at least 24 hours.
- Retry at one layer only, and pass the remaining deadline downstream so no service keeps working on a request its caller has abandoned.
- Cap retries with a budget, for example 10% of requests, and open a circuit breaker while the error rate stays high.
- Make queue consumers idempotent as well; brokers redeliver by design (see Message queues).
You get
- Transient faults that users never see
- Safe client retries across network failures
- Exactly-once effects on top of at-least-once delivery
You pay
- Key storage and a lookup on every write
- Extra latency from backoff on the failure path
- Careful design of what counts as "the same request"
Rule of thumbEvery mutating endpoint accepts an idempotency key, every client retries with backoff and jitter inside a deadline, and exactly one layer owns retries.
Distributed transactions
Keep data consistent when one business operation spans several databases or services that can each fail on their own.
Inside one database, a transaction gives you atomicity for free. Once placing an order touches an orders database, a payments service, and an inventory service, there is no shared transaction to roll back. There are three tools: coordinate one commit across every participant, split the operation into local steps that can be undone, or make one local write the source of truth and propagate it reliably with the outbox pattern.
Two-phase commit has a coordinator ask every participant to prepare and vote, then tells all of them to commit only if every vote was yes. It is atomic, but participants hold locks across network round trips, and if the coordinator crashes after the prepare phase they stay blocked until it recovers. It works best inside one distributed database such as Spanner or CockroachDB, whose coordinators are themselves replicated with consensus, and rarely across independently owned services.
A saga runs a sequence of local transactions, one per service. If a step fails, the saga runs compensating actions for the steps that already completed, in reverse order. Sagas hold no cross-service locks and stay available, but intermediate states are visible: another request may see an order whose stock is reserved but not yet paid for.
Orchestration vs choreography
In an orchestrated saga, one coordinator, often a workflow engine such as Temporal or AWS Step Functions, tells each service what to do next and records progress durably, so the whole flow is readable in one place. In a choreographed saga, services react to each other's events with no central controller. Choreography has fewer moving parts for two or three steps. Beyond that, the flow becomes hard to trace and change, and orchestration usually wins.
| Approach | Consistency | Availability | Use when |
|---|---|---|---|
| Single database transaction | Atomic and isolated | Bound to one database | Everything fits in one database. Try hard to keep it that way. |
| Two-phase commit | Atomic | Blocks if the coordinator fails | Inside one distributed database, or a few tightly controlled participants |
| Saga | Eventual; intermediate states are visible | High, no cross-service locks | Long-running business flows across services |
| Outbox + CDC | One write is the source of truth; others follow | High | Propagating a committed change to other systems |
Production checklist
- Make every step and every compensation idempotent with an idempotency key; the orchestrator will retry them.
- Design compensations as business actions (refund, release, cancel with a reason), not database rollbacks.
- Order the steps so the ones most likely to fail, such as fraud checks and stock reservation, run before the ones that are hardest to undo, such as charging a card or shipping.
- Counter the missing isolation with semantic locks: mark records
PENDINGso other flows know not to act on them yet. - Publish events through an outbox; never write to the database and publish to a broker as two separate steps.
You get
- Consistency across services without a shared database
- Availability while a participant is slow or down (sagas)
- An auditable record of every step
You pay
- Intermediate states visible to users and other services
- A compensation to design and test for every step
- A workflow engine or event plumbing to operate
Rule of thumbKeep data that must change atomically in one database. When a flow has to span services, use an orchestrated saga with idempotent steps and business-level compensations, and publish events through an outbox.
Bloom filters
A compact bit array that answers "definitely not in the set" or "probably in the set," using a few bits per item.
A Bloom filter is an array of m bits, all starting at zero, plus k hash functions. To add an item, hash it k times and set those bits. To check an item, hash it the same way: if any of those bits is 0, the item was never added. If all of them are 1, it probably was, but other items may have set those bits. That is a false positive. There are no false negatives, and a standard filter can't delete items.
The value is in the work it lets you skip. An LSM-tree store such as RocksDB, Cassandra, or HBase keeps a Bloom filter for each on-disk file, so a lookup for a missing key avoids almost every disk read. Chrome once used one to check URLs against its Safe Browsing list locally, and Akamai uses them so its caches only store objects requested more than once. Try it below with 20 bits and 3 hash functions.
Sizing
For n items and a target false-positive rate p, the optimal size is m = −n ln p / (ln 2)² bits, with k = (m/n) ln 2 hash functions. That works out to about 9.6 bits per item for 1%, and every extra 4.8 bits per item cuts the rate by another factor of ten. A billion keys at 1% fit in about 1.2 GB, far less than a hash set of the keys themselves.
| Target false-positive rate | Bits per item | Hash functions | Memory for 100 M items |
|---|---|---|---|
| 1% | 9.6 | 7 | 120 MB |
| 0.1% | 14.4 | 10 | 180 MB |
| 0.01% | 19.2 | 13 | 240 MB |
Variants
- Counting Bloom filters replace each bit with a small counter so items can be removed, at three to four times the memory.
- Cuckoo filters support deletion and use less space than a Bloom filter at false-positive rates below about 3%.
- Scalable Bloom filters chain progressively larger filters when n isn't known in advance. RedisBloom's
BF.RESERVEdoes this with an expansion factor. - To count distinct items rather than test membership, use HyperLogLog.
Production checklist
- Size the filter for the number of items it will hold at the end of its life. Past capacity, the false-positive rate climbs steeply.
- Use it only where a false positive costs a little extra work, such as one unnecessary disk read, never where it produces a wrong answer.
- Rebuild periodically, or use a cuckoo or counting variant, if items expire or get deleted.
- Use fast non-cryptographic hashes such as xxHash or Murmur3, and derive all k positions from two hashes (double hashing).
You get
- Constant-time membership checks at a few bits per item
- Small enough to keep in memory or ship to clients
- Filters of the same size merge with a bitwise OR
You pay
- False positives that grow as the filter fills
- No deletion or listing of items in the basic form
- Capacity that must be chosen up front
Rule of thumbPut a Bloom filter in front of any expensive lookup that usually returns "not found," size it for its final item count, and make sure a false positive only costs a wasted check.
Monolith vs microservices
Split a system into independently deployed services when team, scaling, or isolation needs demand it, not before.
A monolith is one deployable unit. Calls between modules take nanoseconds, one database transaction covers any change, and one stack trace shows the whole request. Its costs grow with the organization: dozens of teams queue behind one release, a bug in one module can take down everything, and the application scales only as a whole.
Microservices give each team a service it deploys on its own schedule, with its own data store and scaling profile. The price is that every module boundary becomes a network boundary. Calls time out, fail halfway, or arrive twice; what used to be a join becomes an API call or a replicated copy; and one user request may cross ten services whose logs live in ten places. Draw service boundaries along bounded contexts, and let each service own its data outright. Services that share tables form a distributed monolith.
The useful middle: a modular monolith
Most teams are best served by a modular monolith first: one deployable, but with modules that own their tables and talk only through explicit interfaces, with those boundaries enforced by build tooling. It keeps the operational simplicity of a monolith and makes a later split mechanical. When a module does need to leave, extract it with a strangler fig migration, one route at a time, rather than a big-bang rewrite.
| Signal | Favors a monolith | Favors services |
|---|---|---|
| Teams | One to a few teams | Many teams blocked on each other's releases |
| Scaling | Load spread evenly across features | One component needs 10× the resources or different hardware |
| Failure isolation | Failing together is acceptable | A non-critical feature must never take down checkout |
| Data | Most operations need cross-module transactions | Clear ownership; cross-boundary consistency can be eventual |
| Platform maturity | No per-service CI/CD, tracing, or on-call | Automated deploys, tracing, and on-call per service |
Production checklist
- Give every service its own datastore and publish changes as events. Never let another service read your tables.
- Budget synchronous call chains. With five sequential hops, about 5% of requests hit at least one hop's p99; move anything off the critical path to asynchronous events.
- Handle cross-cutting concerns (mTLS, retries, telemetry) in the platform through a service mesh or shared libraries, not by hand in every service.
- Version APIs and keep them backward compatible; you can't deploy a service and all of its callers at the same instant.
- Put distributed tracing in place before the split, not after the first cross-service incident.
You get
- Independent deploys and team autonomy
- Per-service scaling and technology choices
- A smaller blast radius when something fails
You pay
- Network latency and partial failure on every call
- No cross-service transactions or joins
- A platform to run: CI/CD, discovery, tracing, and on-call per service
Rule of thumbStart with a modular monolith with strict internal boundaries. Extract a service when a team, scaling, or isolation need is concrete, and give it its own data from day one.
Observability
Instrument a system so you can answer new questions about its production behavior without shipping new code.
Three signals do most of the work. Metrics are cheap numeric time series (request rate, error rate, latency histograms, saturation) that drive dashboards and alerts. Logs record discrete events in detail; structured JSON with a request ID is searchable, free-form strings mostly aren't. Traces follow one request through every service it touches as a tree of timed spans, which makes distributed tracing the practical way to find where the time went.
Start every service with the RED metrics: Rate, Errors, and Duration of requests. For resources such as pools, queues, and disks, add USE: Utilization, Saturation, and Errors. Record latency as histograms rather than averages so you can compute a fleet-wide p99, and watch label cardinality: a user_id label creates one time series per user and can take down the metrics backend.
SLOs and error budgets
A service level indicator (SLI) is a measured ratio, such as the share of requests served successfully in under 300 ms. An SLO sets a target for it over a window, for example 99.9% over 30 days. What's left over is the error budget. While budget remains, ship features; once it's spent, reliability work comes first. Pick a target to see what it allows.
- Per 30 days
- 43 min 12 s
- Per week
- 10 min 5 s
- Per day
- 1 min 26 s
Alert on symptoms, not causes
Page a person when users are affected, as measured by the SLO, not when a CPU graph looks high. Multi-window burn-rate alerts do this well: page when the budget is burning 14.4 times faster than sustainable over both the last hour and the last five minutes, and open a ticket for slower burns. Everything else belongs on a dashboard.
Production checklist
- Propagate W3C
traceparentheaders through every hop, including message queues, and put the trace ID in every log line so you can jump from a log to its trace. - Instrument with OpenTelemetry so you can change backends without re-instrumenting.
- Sample traces deliberately: keep every error and slow request (tail-based sampling) and a small percentage of the rest.
- Keep metric labels bounded, using route templates such as
/users/:idrather than raw paths. Put high-cardinality detail in logs and traces. - Write SLOs for the user journeys that matter (sign-in, search, checkout) and review the error budget when planning work.
You get
- Faster detection and diagnosis of incidents
- Objective reliability targets that balance speed and stability
- Answers to questions nobody anticipated
You pay
- Telemetry ingest and storage, often a noticeable share of the infrastructure bill
- Instrumentation and label discipline across every team
- Ongoing alert tuning to avoid fatigue
Rule of thumbMeasure what users feel: RED metrics on every service, traces across every hop, and SLO burn-rate alerts as the only thing that pages.
Case study: URL shortener
Design a service that turns long URLs into short links and redirects billions of clicks, using the ideas from every earlier page.
Requirements and estimates
Users create a short link such as sho.rt/aZ3kQ9x for a long URL, optionally with a custom alias and an expiry date. Anyone who opens the short link is redirected. Assume 100 million new links a month and 100 redirects for every link created.
| Quantity | Estimate | Consequence |
|---|---|---|
| Writes | 100 M a month ≈ 40 per second, a few hundred at peak | One database leader could take this; the reads are the hard part |
| Reads | 10 B a month ≈ 4,000 per second, 20,000+ at peak | The redirect path must be served from cache |
| Storage | 6 B links over 5 years × ~500 bytes ≈ 3 TB | Shard by code, replicate each shard |
| Key space | 7 base62 characters = 62⁷ ≈ 3.5 trillion codes | Hundreds of times more codes than we'll ever need |
Generating short codes
Hashing the long URL and keeping the first seven characters gives identical URLs the same code, but needs a collision check on every insert. A counter can't collide: allocate unique integer IDs and base62-encode them. To avoid a round trip per link, each app server leases a block of, say, 10,000 IDs from etcd (see Consensus with Raft) and hands them out locally. Sequential codes are easy to enumerate, so scramble each ID with a reversible permutation before encoding.
Creating a link is a write that must not happen twice on a retry, so the create endpoint accepts an idempotency key. Custom aliases need a uniqueness guarantee, which a conditional insert on the shard that owns the alias provides.
The redirect path
Reads outnumber writes 100 to 1, so the redirect is a cache-first lookup. The app checks Redis for the code (cache-aside with a TTL), falls back to the database on a miss, and responds. The database lookup is by code, so shard it by a hash of the code and every read touches exactly one shard. A link that goes viral is a hot key; a short-lived in-process cache on each app server absorbs it.
The status code is a product decision. A 301 is cached by browsers, so repeat clicks never reach you: cheap, but you lose click counts and can never change the destination. A 302 sends every click back through your infrastructure. Many shorteners return a 302 that the CDN may cache for a few seconds, which absorbs bursts while clicks are still counted from edge logs.
Analytics, abuse, and expiry
- Never update a counter in the database on each redirect. Publish a click event to Kafka, keyed by code so each link's clicks stay in one partition, aggregate with a stream processor, and use a HyperLogLog per link for unique visitors.
- Rate-limit link creation per API key with a token bucket, and check destination URLs against a malware list before accepting them.
- Store
expires_atwith each link, check it on read, and delete expired rows in a background sweep. Never reuse a code, or old links shared years ago will point somewhere new. - Set an SLO on the redirect, for example 99.9% of redirects served in under 100 ms, and alert on its burn rate.
Where each concept shows up
| Concept | In this design |
|---|---|
| Scaling | Stateless app servers behind an autoscaler |
| Load balancing | An L7 balancer with health checks in each region |
| Caching | Redis cache-aside plus a small in-process cache for hot codes |
| Replication & sharding | Link table sharded by hash of the code; each shard has a leader and followers |
| CAP & consistency | Alias creation is linearizable; click counts are eventually consistent |
| Consistent hashing | Spreading codes across cache nodes (Redis Cluster uses a fixed 16,384-slot table, a close cousin) |
| Message queues | Click events in Kafka, keyed by code |
| Rate limiting | Token bucket on link creation per API key |
| CDNs & edge caching | Short-lived edge caching of 302 responses |
| Consensus with Raft | etcd leases ID ranges to app servers |
| Idempotency & retries | Idempotency keys on link creation |
| Bloom filters | A filter of taken aliases tells users an alias is free without a database read |
| Observability | An SLO on redirect latency, with burn-rate alerts |
You get
- Redirects served from the edge or cache in milliseconds
- Horizontal scale on every tier
- Analytics that can't slow down or break redirects
You pay
- Click counts that lag by seconds
- More traffic with 302s than with 301s
- ID leasing and cache invalidation on edits to operate
Rule of thumbDesign the hot path first. For a read-heavy service that means the redirect: edge, cache, a single-shard lookup, and nothing synchronous that isn't needed to answer.