Scalability Patterns and Techniques Questions
Scaling a system to handle growth in traffic and data: horizontal versus vertical scaling, statelessness, sharding and partitioning strategies, read replicas, and connection pooling. Covers capacity estimation, identifying bottlenecks, and the tradeoffs each scaling axis introduces. The general toolkit for taking a design from thousands to millions of users.
Your relational database allows a maximum of 500 concurrent connections. Your application runs on 25 identical JVM instances plus 3 background job workers. Walk through how you'd compute a safe default connection-pool size per instance, the factors you'd weigh, and your recommended pool size. What would you monitor, and what would you do if you saw connection saturation in production?
Sample Answer
Direct answer
Work backward from the database's hard ceiling, not forward from a per-instance number that feels generous. Reserve headroom for admin connections, failover, and bursts, divide what remains across every process that opens a connection (application instances and background workers alike), and floor the result. For 25 application instances (each running as its own process, commonly a JVM, a Java Virtual Machine, instance) plus 3 background workers against a 500-connection ceiling, that works out to a safe default of 14 connections per process, with room to tune down from there once you have real utilization data.
Structured elaboration
The formula
- Total connection-opening processes: 25 application instances + 3 background workers = 28.
- Reserve headroom for database maintenance tooling, admin connections, and burst capacity: a common starting assumption, stated here as a planning input rather than a measured fact, is 20%, leaving 80% of the ceiling as usable pool capacity.
- Safe per-process pool size: divide usable capacity across all processes and round down, so no single process's pool can push the fleet over the ceiling if every process is fully utilized simultaneously.
usable=500×0.80=400
per-process pool=⌊28400⌋=⌊14.29⌋=14
Factors that push the number up or down
- Transaction duration: long-running transactions hold a connection for longer, so a workload with slow queries needs a smaller pool per process (or faster queries) to avoid connections queuing up behind a few slow holders.
- Background workers are often burstier than request-serving instances; giving them the same per-process budget as application instances can be wasteful most of the time and insufficient during a burst. A separate, smaller steady-state budget with the ability to borrow from an external pooler (below) handles this better than a single uniform number.
- Read-heavy workloads can shift some of this load to read replicas, reducing the connection pressure on the primary specifically.
- Connection acquisition overhead and idle timeout settings affect how much of the pool is actually "available" at any moment versus tied up in idle-but-not-yet-reaped connections.
Monitoring and response to saturation
- Track: active connections per process, pool wait count and wait time, database-side connection count versus the 500 ceiling, and application-level timeout errors on connection acquisition.
- Alert when pool utilization sustains above roughly 75%, or when any request has to wait for a connection for more than a short, explicitly agreed threshold.
- On saturation: first apply backpressure (queue or reject new work rather than let requests pile up waiting on connections), then check whether the pool size itself is oversized relative to actual concurrent demand (overcommitted pools waste database-side capacity even when the app-side pool looks "full" only occasionally), then consider moving read traffic to a replica, and only then treat raising the database's connection ceiling or adding an external pooler as the longer-term fix.
Worked example
The formula above holds at moderate fleet size, but it breaks down as the fleet grows faster than the database's connection ceiling. Assume, again as a planning input, a fleet that has grown to 200 identical instances against a database with a 1,000-connection ceiling. Applying the same approach:
usable=1000×0.80=800
per-instance pool=⌊200800⌋=4
Four connections per instance is thin: if a single instance briefly needs more than four concurrent database calls, for example during a request burst, it will queue locally even though the database as a whole has spare capacity sitting idle in other instances' unused pool slots. This is also exactly the scenario where a rolling deploy becomes dangerous: if all 200 instances restart in a short window and each immediately tries to open its full pool of 4 connections, that is a connection storm, a spike toward the 1,000-connection ceiling driven by simultaneous reconnects rather than steady-state load, and it can exhaust the ceiling before the deploy even finishes.
The fix at this scale is usually an external pooler such as PgBouncer, placed between the 200 application instances and the database, multiplexing many app-side connections onto a much smaller database-side pool. PgBouncer's two relevant modes make different trade-offs:
- Session pooling mode: a database connection is assigned to one client connection for its entire session (until it disconnects). This preserves session-scoped features like prepared statement caching and
SETcommands, but it does not reduce database-side connections below the number of concurrently active client sessions, so it does not solve the 200-instances-against-1,000-connections problem by itself. - Transaction pooling mode: a database connection is held only for the duration of a single transaction, then released back to the pool immediately for another client to use. This lets a small database-side pool (for example, 50 to 100 connections) serve far more app-side connections than session mode can, at the cost of breaking anything that relies on session state persisting across transactions, such as advisory locks held between transactions or
SET-scoped session variables.
Given the transaction-pooling trade-off, a deploy in this configuration should also stagger restarts (for example, capping simultaneous restarts to a small percentage of the fleet with a ramp-up delay between batches) rather than restart all 200 instances at once, regardless of whether an external pooler is in place.
Trade-offs & pitfalls
- Sizing the pool from "what feels safe" rather than the database's actual ceiling is the most common mistake: it works until a deploy, a traffic spike, or a new service instance pushes the fleet over the limit all at once.
- A pool that is too large per instance doesn't help throughput once the database itself is saturated; it just moves the queue from the application to the database, where diagnosing it is harder.
- An external pooler adds an operational dependency and a new failure mode (the pooler itself can become a bottleneck or single point of failure) in exchange for solving a problem the simple per-instance formula cannot solve at high instance counts.
- Any pool-sizing decision should be re-validated with load testing and real monitoring data, not treated as a one-time calculation; traffic mix and query patterns change the safe number over time.
A cost-conscious SaaS customer has highly spiky traffic, roughly a 10x daily swing. How would you pick instance types and an autoscaling policy that keeps P95 latency on target while minimizing cost? Discuss reserved versus spot instances, burstable instances, predictive versus reactive scaling, and container versus VM-based scaling.
Sample Answer
Direct answer
For a 10x daily traffic swing, reserve baseline capacity for the trough, autoscale the delta up to peak, and lean predictive/scheduled scaling over purely reactive, since a daily swing is exactly the regular, forecastable pattern predictive scaling is good at. Use burstable instances only where bursts are genuinely short; use spot for stateless, interruption-tolerant work; keep on-demand or reserved capacity for the latency-critical path. The instance and purchasing decisions matter less than getting this basic shape right: match committed spend to the floor, elastic spend to the swing.
Structured elaboration
Reserved vs. spot vs. on-demand
- Reserved (or savings-plan) capacity for the steady trough load, since that portion runs 24/7 regardless of the swing and benefits most from a committed discount.
- Spot for stateless, horizontally-scaled, interruption-tolerant work (background/batch consumers), paired with graceful draining so an interrupted instance doesn't corrupt in-flight work.
- On-demand as the buffer for latency-critical capacity above the reserved baseline, and as an immediate fallback when spot capacity is reclaimed.
Burstable vs. fixed instances. Burstable instances (which accumulate CPU credit during idle periods and spend it during bursts) are worth using only if the burst is genuinely short relative to how fast credits accumulate; a 10x swing that holds for hours, not minutes, will exhaust accumulated credit and fall back to a throttled baseline performance level, which is the opposite of what you want during peak. For a sustained multi-hour peak, more numerous smaller fixed instances scaled horizontally is the safer choice.
Predictive vs. reactive. A daily 10x swing is about as regular a pattern as autoscaling ever sees, which makes it a strong candidate for scheduled/predictive pre-scaling: scale up ahead of the known daily ramp rather than waiting for a reactive trigger to catch up. Keep a reactive, latency-based layer running underneath as the backstop for whatever the schedule gets wrong on an atypical day (a P95 latency target, the 95th-percentile response time, i.e. the value 95% of requests come in under, is a good backstop metric since it reflects what users actually feel).
Containers vs. VMs. A container platform with a cluster autoscaler can bin-pack (efficiently pack workloads of different sizes onto the fewest possible shared machines, matching each workload's resource need to available capacity the way you'd pack differently-sized boxes into as few shipping crates as possible) across mixed instance types (reserved, on-demand, spot) on shared nodes and starts new replicas faster than a fresh VM boots, which matters directly for how quickly the fleet can absorb the ramp into peak. Plain VM-level autoscaling is simpler operationally but coarser-grained and slower to provision; it's a reasonable choice when multi-tenant isolation or licensing requirements rule out sharing nodes.
Worked example
Total cost of ownership (TCO) comparison: fixed peak-sized warm capacity vs. autoscaling. Assume, as stated planning inputs, not measured figures: peak load requires 100 instances for 4 hours/day, trough load requires 10 instances for the remaining 20 hours/day, over a 90-day (roughly 3-month) window, at an illustrative $0.10/instance-hour.
Fixed warm capacity sized to peak, running at 100 instances around the clock:
100×24×90×$0.10=$21,600Autoscaling between trough and peak:
(100×4+10×20)×90×$0.10=600×90×$0.10=$5,400 $21,600$5,400=0.25In this illustrative model, autoscaling costs a quarter of what permanently warm peak-sized capacity would, a $16,200 saving over 3 months. That gap is exactly why "just overprovision and stop worrying about it" is rarely the right default for a regular, predictable swing like this one; it's a defensible fallback only when the swing is irregular enough that autoscaling reliably can't keep up, which a stable daily pattern isn't. (This simplified model ignores scale transition costs and the risk of a slow ramp missing the service level objective, SLO, the measurable target committed to for latency or availability; a real sizing exercise would validate the ramp time against the actual latency budget by load-testing the actual scale-out ramp: confirming that a newly-scaled instance passes its health check and starts serving real traffic before the P95 latency budget for that request is exhausted, not just that the instance count eventually reaches the target.)
Fast, extreme burst: 1-hour marketing spike from 1,000 to 100,000 requests per second (RPS). A daily-swing policy tuned for a gradual 10x ramp is the wrong tool for a sudden, 100x, hour-long spike: neither reserved nor on-demand compute autoscaling reacts fast enough on its own at that magnitude. Layer the response instead: put a content delivery network (CDN, a network of edge servers caching content close to users) in front to offload whatever fraction of that traffic is cacheable, entirely off origin compute; use serverless (functions as a service, FaaS, where the platform scales invocation concurrency per-request rather than per-instance) or a pre-warmed burst pool to absorb the residual dynamic traffic within the 1-hour window, since compute autoscaling alone is too slow to react meaningfully inside that timeframe.
Bursting to a second region vs. permanent capacity. For a short or infrequent peak, temporarily bursting overflow traffic to a second region avoids paying for duplicate capacity that sits idle everywhere the rest of the time, but it only works if the service can actually run statelessly in a freshly-spun-up region and if the operational readiness (data replication, DNS or traffic-shifting mechanics) was built and tested ahead of time, not improvised during the peak. Provisioning a single larger region permanently is simpler operationally but pays for that simplicity around the clock; the second-region approach trades operational complexity for lower steady-state cost, which is worth it exactly when the peak is genuinely short or rare.
Trade-offs & pitfalls
- Burstable-instance credit exhaustion under a sustained (not brief) peak silently degrades performance right when peak matters most; validate actual burst duration against credit accumulation before relying on this instance class for a multi-hour swing.
- Spot capacity is only appropriate for the fraction of the fleet that tolerates interruption; putting latency-critical serving on spot to save cost trades away exactly the reliability the SLO depends on.
- Predictive scaling tuned to a daily pattern will under-react to anything that isn't the daily pattern (a genuine spike layered on top of the normal swing); it needs the same kind of reactive, latency-based backstop described above for the daily-swing case: a layer that watches P95 latency directly and scales further whenever the schedule under-predicts, rather than assuming the daily schedule alone is sufficient.
- A cost comparison like the TCO example above is only as good as its throughput-per-instance and hours-at-peak assumptions; treat those as inputs to validate against real load tests, not numbers to trust by default.
When should you reach for asynchronous processing in a cloud architecture? Give examples of tasks that belong on a queue, the benefits and trade-offs (latency, throughput, complexity), and how you'd choose between a simple message queue, a pub/sub system, and a streaming platform for different workloads.
Sample Answer
Direct answer
Reach for asynchronous processing when a task doesn't need to block the user's response, has variable or long duration, benefits from being retried independently of the request that triggered it, or needs to scale at a different rate than the request path that produces the work. The trade-off is always the same shape: lower perceived user latency and higher burst-absorption capacity, in exchange for longer end-to-end completion time and real added complexity (idempotency, ordering, observability).
Structured elaboration
Tasks that belong on a queue: long-running jobs (video transcoding, PDF generation, model training), background work (email/SMS delivery, webhook retries, batch extract-transform-load jobs), rate-limited external calls (payment-gateway retries respecting a provider's own limits), and fan-out work (thumbnail generation, notification distribution to many recipients).
Benefits versus trade-offs:
| Dimension | Sync | Async |
|---|---|---|
| Perceived latency | Higher (user waits for the full task) | Lower (user gets an immediate acknowledgment) |
| End-to-end completion | Bounded by the request | Can be longer; work finishes on its own timeline |
| Throughput under burst | Limited by request-handling capacity | Higher; a queue absorbs bursts the request path can't |
| Complexity | Lower | Higher (idempotency, ordering, retry/dead-letter queue (DLQ), status tracking, monitoring) |
Choosing the messaging technology:
- Simple message queue (point-to-point task queue with retry semantics, one consumer per message): use for straightforward background jobs where ordering isn't required.
- Pub/sub (one message, many independent subscribers): use for event-driven fan-out across decoupled services, where each subscriber reacts to the same event differently.
- Streaming platform (ordered, replayable log, supports stateful consumers): use when ordering, replay, or exactly-once-style processing semantics matter, such as event sourcing or analytics pipelines.
Decision checklist: need ordering or replay, use streaming; need to fan out to many independent consumers, use pub/sub; need a simple worker queue with retries and nothing fancier, use a message queue.
Worked example
Migrating an existing synchronous pipeline to async: a concrete pilot. Say order-confirmation emails are currently sent synchronously inside the checkout request handler, adding real latency to checkout and coupling checkout availability to the email provider's uptime. The migration:
- Introduce a queue behind the checkout handler; the handler publishes an "order confirmed" message and returns to the user immediately instead of waiting on the email call.
- Define an idempotency key (the order ID) so that if the message is redelivered (a realistic possibility under at-least-once delivery), the consumer can detect and skip a duplicate send rather than emailing the customer twice.
- Decide on ordering: for this task, per-order ordering doesn't matter across different orders, so no partition-by-key requirement beyond what's needed for the idempotency check itself.
- Add a bounded retry (say, 3 attempts with backoff) and a DLQ for emails that still fail, so a transient provider outage doesn't silently drop confirmations.
- Pilot on a low-traffic checkout path first, and communicate the user-facing change explicitly: the email is no longer guaranteed to have been sent by the time the checkout page renders, which may require a small copy change ("confirmation email on its way" rather than implying it already arrived).
Precompute layer for a legacy synchronous aggregation service. A service that computes an expensive aggregate (say, a rolling usage summary) synchronously on every request can be converted to a precompute pattern: an async job recomputes the aggregate on a schedule or on a triggering event and writes it to a fast-read store; the read path serves from that store. On a cache miss (a query for a window that hasn't been precomputed yet, common right after rollout), the service falls back to computing it synchronously that one time and warms the cache with the result, so misses shrink over time instead of recurring. A one-time backfill job for historical windows at rollout avoids a long tail of slow cache-miss requests immediately after launch.
Batch versus online inference for ML serving. The same sync-versus-async trade-off shows up in model serving: batch (async) inference runs predictions over a group of inputs on a schedule or triggered job, giving higher throughput and lower cost per prediction at the expense of staleness equal to the batch interval; online (sync) inference serves a live request through the model on the request path, giving the freshest possible result but bounded by a per-request latency budget and a harder cost curve to scale at high request volume. The choice depends on whether the feature consuming the prediction can tolerate staleness measured in minutes or hours, or genuinely needs a fresh result per request.
Trade-offs & pitfalls
- Skipping idempotency is the single most common mistake in this pattern. At-least-once delivery is the realistic default for most queueing systems; a consumer that isn't safe to run twice on the same message will eventually double-charge, double-send, or double-write something.
- Ordering requirements are easy to miss until they bite. If two messages about the same entity can be processed out of order and produce a different, wrong final state, that entity's messages need to be routed to preserve order (typically via a partition key), which the simplest queue setups don't guarantee by default.
- The user-facing latency change needs to be communicated, not just implemented. Moving a task from synchronous to asynchronous changes what "done" means from the user's perspective; shipping that silently creates confusing, inconsistent-feeling product behavior even when the backend change is technically correct.
- A precompute layer with an unbounded cache-miss fallback can silently degrade into "synchronous, but slower and more complex." If misses stay common because a backfill never ran, or the precompute schedule can't keep up with query patterns, you've added the complexity of async without capturing its latency benefit.
Explain the session-management options available once you're operating at scale: sticky sessions (session affinity at the load balancer) versus externalizing session state to a shared store such as Redis or DynamoDB. Discuss the trade-offs around failover, consistency, latency, throughput, session size, security, and operational cost in a multi-region deployment.
Sample Answer
Direct answer
Once you scale past a handful of instances, in-memory session state stops working: sticky sessions (routing every request from a user to the same backend instance) keep working but make the fleet fragile and hard to rebalance, while externalizing session state to a shared store (Redis, DynamoDB, or similar) makes every instance stateless at the cost of a network hop and a new piece of infrastructure to run. For most cloud-native, multi-region systems the externalized store wins once you account for failover and elastic scaling, but the right choice depends on session size, read/write rate, and how much latency and operational cost you can absorb.
Structured elaboration
Sticky sessions (load-balancer affinity)
The load balancer hashes a client identifier (cookie or IP) to consistently route it to one backend instance, which keeps the session data in that instance's local memory. This is the load-balancer mechanism; the algorithm and health-check details behind it belong to load-balancing design, not to this decision. What matters here is the state-management consequence: the instance becomes a single point of failure for every session pinned to it.
Externalized session store
The application writes session data to a shared store instead of local memory, so any instance can serve any request. This is what makes the fleet stateless and lets you autoscale, blue/green deploy, and route traffic freely.
Trade-off table
| Dimension | Sticky sessions | Externalized store |
|---|---|---|
| Failover | Session lost on instance failure unless replicated; rebalancing during deploys/scaling causes cold sessions | Store durability decoupled from app instances; use a replicated cluster (Redis with replica failover, or DynamoDB global tables) so an app instance failing loses nothing |
| Consistency | Trivially strong (session lives in one place) | Depends on the store: Redis is effectively strongly consistent per key against its primary; DynamoDB gives you a choice of eventually-consistent or strongly-consistent reads |
| Latency | Lowest possible (in-process memory read) | One extra network hop; mitigate with a colocated cache or read-through caching in front of the store |
| Throughput | Scales with instance count but capacity is uneven per node | Redis and DynamoDB both scale horizontally; DynamoDB in particular scales writes by adding capacity/partitions |
| Session size | Cheap for small payloads, but large sessions inflate instance memory and slow instance startup/warm-up | Better suited to larger or shared sessions; still keep the session small (store a reference token, not a blob, where possible) |
| Security | Session data lives on the app host itself, so host-level compromise exposes it | Data is centralized, which is a bigger target but also a single place to enforce encryption at rest/in transit, network isolation, and access control |
| Operational cost (multi-region) | Simple to run but scales poorly for global traffic and breaks under cross-region failover | Higher baseline cost (a cluster to run, replicate, and monitor) but the one that actually supports multi-region deployment |
Two problems specific to externalizing state that a senior candidate should raise
- Data locality/regulatory constraints on where the store lives. Once session state leaves the process and lives in a shared store, where that store is physically located becomes a compliance question in a way it never was for sticky sessions. If you operate in a jurisdiction with a data-residency requirement (for example, keeping EU user data on EU infrastructure), the session store's region placement is now something you have to design around explicitly: either run per-region session stores keyed so a user's session never leaves their region, or make sure the store you pick supports region-pinned partitions. This is a design constraint, not an afterthought bolted on after the store is chosen.
- Token revocation/invalidation once you drop server-side sticky sessions. With sticky sessions, "logging a user out" or forcibly invalidating a session is trivial: the state lives in one place and you delete it there. Once you move to a stateless architecture backed by client-held tokens (JWTs, JSON Web Tokens), you lose that for free, because a JWT is self-contained and valid until it expires, regardless of what the server thinks. You need an explicit revocation mechanism: keep a server-side allow/deny list (defeats some of the point of a stateless token, but is often still cheaper than full session storage), keep JWT lifetimes short and pair them with a refresh-token that IS checked against the store on each renewal, or store only a session identifier in the token and look up the actual session state (and its revocation flag) in the externalized store on every request. Whichever you pick, decide it up front: it is the first thing that breaks in incident response ("how do we kill this user's access right now") if you didn't.
Worked example
A mid-size SaaS product runs 40 stateless application instances behind a load balancer in two regions (US and EU) for latency and the EU data-residency requirement above. Session state (user id, cart contents, feature flags, roughly 2 KB per session) is stored in a regional Redis cluster with cross-region replication disabled by design, so an EU user's session data never crosses into the US store. Each app instance reads the session on request start and writes it back on request end; a local, short-time-to-live (TTL) cache in front of Redis (5 seconds) absorbs the read traffic for users making several requests per second, so the added latency in the common case is effectively the local cache lookup, not a Redis round trip. Auth uses short-lived JWTs (a few minutes) plus a longer-lived refresh token that is checked against the Redis-backed session record on every refresh; revoking a user (support ticket, password reset, or a fraud flag) sets a revoked flag on that record, so their access token stops renewing once it expires and, for the small number of write-sensitive endpoints, is checked directly against the record on every call. This gives the team elastic autoscaling and blue/green deploys without cold-session churn, at the cost of running and monitoring two regional Redis clusters instead of zero.
Trade-offs & pitfalls
- Reflexively "always externalize" is a mistake for small, low-scale, or lift-and-shift systems where the operational cost of running a session store isn't yet justified; sticky sessions with a short-TTL fallback can be the pragmatic starting point.
- Under-provisioning the session store's replication is the most common failure: teams externalize state assuming it fixed failover, then discover the store itself is a new single point of failure because they ran it as a single node.
- Storing large or unbounded session payloads in the shared store (shopping-cart history, uploaded-file references) rather than keeping sessions small and pushing bulk data to its own store is a frequent scaling mistake that shows up as store memory pressure and slow serialization, not as an obvious session bug.
- Treating token revocation as solved by "just make JWTs short-lived" without also handling the case where a token must be killed immediately (compromised account) is a common gap; short expiry reduces the blast radius but does not give you an immediate kill switch on its own.
A user request traverses six microservices. How would you measure and attribute its P95/P99 tail latency, and what would you do to reduce it? Cover your instrumentation and sampling/tracing strategy, how you'd detect a spike, and mitigation techniques such as hedged requests, request prioritization, resource partitioning, and admission control.
Sample Answer
Direct answer
Measuring tail latency across six hops means separating two questions: which hop is actually responsible for a given slow request (attribution), and is the tail getting worse over time (detection). Attribution needs per-hop distributed tracing with sampling that preserves slow traces even when it drops fast ones; detection needs P95/P99 (95th- and 99th-percentile latency, the response times only the slowest 5% and 1% of requests exceed) tracked as their own alertable series, since a stable median (this is the common trap: P99 spikes while the median looks completely healthy) hides exactly this class of problem. Once a hop is identified, the fix is rarely "make everything faster" but a targeted mitigation such as hedged requests, request prioritization, resource partitioning, or admission control aimed at that specific hop, each of which trades some cost or complexity for the latency it buys back.
Measurement and attribution
- Instrumentation: every one of the six services emits a span per request with start/end timestamps, propagated trace context, and enough metadata (host, downstream call outcome, queue wait time) to distinguish "this hop was slow" from "this hop was waiting on the next one."
- Sampling strategy: pure random sampling at low rates (say 1%) will almost never happen to capture a P99 request, since by definition only 1% of requests qualify and the sample and the tail rarely overlap. Use tail-preserving (tail-based) sampling: buffer a trace briefly and only decide to keep it once you know whether any span exceeded a latency threshold, so slow traces are captured close to 100% of the time while typical traces are still sampled cheaply.
- Attribution: once a slow trace is captured, break its total duration into a waterfall of per-hop contributions to see which hop consumed the largest share.
- Spike detection: alert on the rate of change of P95/P99 against a rolling baseline (for example, a sustained jump relative to the trailing window), not on a single fixed threshold, since normal traffic variation would otherwise cause constant false alarms.
Worked example: attributing a P99 spike across six hops
As an illustrative example, not measured data, suppose a captured slow trace shows an 800 ms end-to-end duration split across the six hops as follows:
| Hop | Contribution to trace duration |
|---|---|
| A (edge/gateway) | 50 ms |
| B (auth/lookup service) | 300 ms |
| C (business logic) | 100 ms |
| D (data-access service) | 150 ms |
| E (enrichment service) | 100 ms |
| F (response assembly) | 100 ms |
| Total | 50+300+100+150+100+100 = 800 ms |
Hop B accounts for 800300=0.375=37.5% of the total, the single largest share, so it is the first place to investigate and the first place a mitigation should target, rather than spreading effort evenly across all six services.
Mitigation techniques, their overhead, and their risk
| Technique | What it does | Operational overhead | Risk |
|---|---|---|---|
| Hedged requests (replica hedging) | Send a second request to a different replica after a short delay if the first hasn't responded; take whichever finishes first and cancel the other | Requires idempotent operations and extra downstream capacity headroom to absorb the duplicate load | Can amplify load during a genuine overload, since a slow dependency triggers hedges everywhere at once; needs a cap on hedge rate or it makes the underlying problem worse |
| Request prioritization (priority queues) | Classify requests as interactive versus batch and schedule interactive traffic ahead of batch at every hop | Every hop in the path must honor the same priority scheme consistently, adding coordination and scheduling complexity | Low-priority traffic can starve entirely if there's no guaranteed minimum share for it |
| Resource partitioning (resource isolation) | Dedicate CPU/memory pools to latency-sensitive services so a noisy batch workload can't steal their resources | Deliberately reduces overall utilization efficiency in exchange for isolation, and adds infrastructure to manage separately | If the partitions are too small or the isolation boundary is drawn at the wrong level, the workloads you meant to separate can still interfere |
| CPU pinning | Bind a hot service's threads to specific cores to reduce cross-core cache misses and scheduler-induced jitter | Removes the scheduler's flexibility to pack other work onto those cores, reducing overall efficiency | Pinning to cores that still share a memory controller or cache with a noisy neighbor gives no benefit while still costing the flexibility; needs revisiting if hardware topology changes |
| GC tuning (garbage-collection tuning) | Reduce allocation rate and favor a pause-time-oriented garbage collector so tail latency isn't dominated by stop-the-world pauses | Requires runtime-specific expertise and ongoing revalidation as code and allocation patterns evolve | Trading pause time for throughput is a real trade, not a free win; a poorly chosen configuration can make both worse |
| Avoiding blocking I/O | Perform network and disk calls asynchronously so a thread isn't held idle waiting on a slow dependency | Async code is harder to write, test, and debug: error propagation and cancellation get more complex | Can hide backpressure (a signal that would otherwise tell the caller to slow down because you can't keep up) if not paired with bounded queues, since a service can accept far more concurrent work than it can actually finish in time |
| Admission control | Reject or shed excess load at the edge before it enters the six-hop path | Needs per-tenant or per-class quotas and clear client-facing signaling (retry-after style responses) | Overly aggressive shedding converts a latency problem into an availability problem for legitimate traffic |
Trade-offs and pitfalls
- Chasing every hop at once instead of attributing first. Without the waterfall breakdown, teams tend to optimize the hop that's easiest to touch rather than the one actually driving the P99.
- Sampling uniformly at a low rate and concluding tail latency "looks fine" because slow traces were simply never captured. The sampling strategy has to be tail-aware, not just cheap.
- Applying hedging without a cap. It is the mitigation most likely to backfire under genuine overload, since it adds load exactly when the system can least afford it.
- Treating any single mitigation here as free. Every row in the table above buys latency at the cost of either infrastructure efficiency, code complexity, or operational risk; picking one should follow from what the attribution step actually showed, not from familiarity with the technique.
Unlock Full Question Bank
Get access to all Scalability Patterns and Techniques interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.