Resource Contention in Production

Leave a rating for Practical System Design on Amazon. (opens in a new tab)
01 · 3/25 · 0%

01Chapter 1

Resource Contention in Production

The product page and the pool
Chapter 1 figure. Product Page calls Catalog and Recommendation through a shared connection pool.

As an engineer, you spend much of your day modifying applications that already serve customers. A product manager might ask you to add a field to an API response, update a database query, or integrate a feature that another team has already developed. You find the relevant code, make the change, write a test, and open a pull request. It is a familiar routine, and most of the time, the change really is that straightforward.

A similar request came to Baodium’s product-page team. The product manager wanted a “Recommended for you” row on every product page, hoping customers would discover other items they might like. Recommendation Service already supplied suggestions for the home page, so the developer reused its existing endpoint. After adding the call, the developer wrote a unit test with a predefined recommendation response, verified that the page displayed the new row, and submitted the change for review.

Everything appeared reasonable. The service was already running in production, the implementation required only a few lines, and the test passed. However, the test had used a predefined response rather than calling Recommendation Service. It confirmed that the product page could display recommendations, but it provided no information about the database requests the service would make when customers started using the feature.

The team also had not established how the new call would affect the time needed to return a product page. Customers could browse or purchase an item without recommendations, yet the developer had placed the call before the page response was built. That meant a customer could end up waiting for recommendations even after the product information was ready.

We can understand why that mattered by looking at the request path before and after the change.

Synchronous Dependencies on the Request Path

Before the feature was introduced, Product Page Service fetched the required product information from Catalog Service and used the result to build the response (Figure Figure).

The original product-page response depended on Catalog Service.
The original product-page response depended on Catalog Service.

The developer added the recommendation lookup immediately after fetching the product. Listing Listing shows the simplified handler.

The product-page handler with the new service call.
Python
def get_product_page(user_id, product_id):
    product = catalog_service.fetch(product_id)
    recs = recommendation_service.get(user_id, product_id)
    return build_response(product, recs)

The sequence is straightforward. Product Page Service requests the product from Catalog Service, retrieves recommendations, and combines both results into the response. The problem appears when the second call takes longer than expected. Even if Catalog Service has already returned the product, the handler cannot send the page until Recommendation Service responds.

Figure Figure shows how that additional call changed the request path.

The recommendation lookup introduced another synchronous dependency.
The recommendation lookup introduced another synchronous dependency.

The product manager had requested another row on the page. There was no requirement for customers to wait for that row before seeing the product, yet the implementation introduced that dependency. The code was functioning as written, and the unit test had no reason to report a failure.

Baodium initially enabled the feature for one percent of eligible customers through a feature flag.1 The Product Page instances checked the flag before calling Recommendation Service, allowing the release owner to increase exposure gradually.

There was a detail the rollout percentage did not capture. One percent of customers does not necessarily generate one percent of product-page requests. A customer who opens twenty products creates far more recommendation calls than someone who visits a single page. The release owner was watching customer exposure, but the team had not established how that exposure translated into traffic reaching Recommendation Service.

During the first few rollout stages, the latency dashboard looked much as it had before the release. As exposure increased, however, the slowest product pages began taking longer while the median changed very little. Seventeen minutes after the first increase, a customer-facing latency alert fired.

The engineers now had an incident to investigate. The new service call was a likely place to begin, although they still needed to establish what was making it slow.

Diagnosing Connection-Pool Saturation

The on-call engineer started by examining the recommendation queries. Their execution times were close to the measurements taken before the release, which made a widespread SQL regression less likely. Those measurements could not rule out every database problem, since some queries might still experience lock waits or unusually long execution times. They did, however, give the engineer a reason to examine what happened before the queries started.

Recommendation Service accessed PostgreSQL through a connection pool. Establishing a database connection requires network setup and authentication, so applications typically reuse existing connections rather than creating a new one for every query. A request acquires a connection, performs its database operations, and returns the connection for another request to use.

The difficulty begins when every available connection is already assigned.

Think of calling a customer-support center where forty agents are serving other customers. Your conversation might take only two minutes once an agent picks up, but you could spend considerably longer in the queue before speaking to anyone. Measuring the length of the conversation would tell us very little about the total time you spent waiting.

Database connection pools have the same distinction. A query can execute quickly once it receives a connection, while the request that submitted it spends much longer waiting to acquire one.

Each Recommendation Service instance had a maximum of 40 database connections. The on-call engineer examined the connection-pool readout for an affected instance (Listing Listing). 2

assigned_connections    40
idle_connections         0
pending_acquisitions    80
acquire_p99             600 ms
query_p99               near baseline
occupancy_mean          70 ms

At the time of the snapshot, all 40 connections were assigned, and another 80 requests were waiting to acquire one. The acquisition p99 was approximately 600 milliseconds during the observation window. In that window, the slowest one percent of successful connection acquisitions took about that long or longer.

Those requests had spent time waiting before their SQL statements could begin. Their acquisition delays therefore did not appear in the query-execution measurements.

We now had evidence that explained why product pages were becoming slower even though the recommendation queries were executing within their usual range.

Connection Acquisition, Execution, and Occupancy

It is useful to distinguish three intervals whenever an application uses a database connection pool.

Acquisition time

The time between requesting a database connection and receiving one from the pool.

Query execution time

The time a SQL statement takes to execute after it starts.

Connection occupancy

The interval from acquiring a connection until returning it, including any time spent between statements or inside a transaction.

These intervals allow us to investigate different causes of latency. When acquisition time increases while SQL execution remains close to its previous range, we can examine how many callers need connections, how frequently requests arrive, and how long each caller occupies a connection. If SQL execution itself becomes slower, query plans, database locks, CPU usage, and storage performance deserve closer attention.

Baodium’s engineers had initially examined the queries because the new feature depended on them. Once they compared execution time with acquisition time, they could see that requests were competing for a limited number of connections. Chapter 8 develops the instrumentation used to make these measurements, including attempts that time out before receiving a connection.

Shared Pools and Fleet-Wide Database Limits

The additional requests came primarily from product pages, but Recommendation Service also served the home page and checkout. All three workloads used the same service instances and their database connection pools.

As product-page traffic increased, home-page and checkout requests could find themselves waiting for connections already assigned to recommendation lookups. A feature intended to improve product discovery was now delaying other customer operations.

During the incident call, one engineer proposed increasing the connection-pool size. Another suggested adding more Recommendation Service instances so the incoming traffic could be distributed across a larger fleet.

Both suggestions deserved consideration. The concern was how much additional demand they would place on PostgreSQL.

Each Recommendation Service instance maintained its own connection pool. If twenty instances each permitted forty database connections, the fleet could establish as many as 800 sessions against the same PostgreSQL server.

PostgreSQL limits the number of sessions it accepts, but that limit does not tell us how many queries the database can execute efficiently at the same time. Those queries still compete for CPU, memory, disk access, and locks. Increasing the number of available connections could therefore allow more concurrent database activity without improving the time needed to complete requests.

The engineers had not yet established how much database capacity Recommendation Service could safely use. Increasing the connection limit during the incident would have introduced another change whose effect they could not predict from the available measurements.

The feature flag offered a more immediate option. Recommendations were an addition to the product page, and customers could still browse or purchase products without them. The release owner could disable personalization and remove the additional requests while the team investigated.

Optional Recommendations and Admission Control

Disabling the feature brought product-page latency back within its previous range. That gave the engineers time to investigate, but the product team still wanted to introduce recommendations.

When they returned to the implementation, the discussion began with what the product page actually needed to provide.

The product manager wanted recommendations to appear on most pages. The engineers needed to protect the product information customers had requested and avoid introducing another waiting queue whenever Recommendation Service became busy.

The team agreed on three requirements.

  1. Under the tested traffic conditions, the product page must meet its latency objective even when recommendations are unavailable.

  2. Recommendations must appear on at least 95 percent of eligible, flag-enabled pages during peak traffic.

  3. Product Page Service must not accumulate a waiting queue for optional recommendations. Recommendation Service must enforce its own database admission limit.

The 95 percent requirement mattered because one possible solution was to omit recommendations whenever the service became busy. That would protect the product page, although it might also remove the feature from a large proportion of customer requests.

The engineers discussed other approaches. Fetching product information and recommendations in parallel could reduce how long an individual page waited, but it would leave the database receiving the same recommendation traffic. Precomputing recommendations could remove many of those live queries, although it would introduce a refresh process, additional storage, and a decision about how recently recommendations needed to be calculated. Chapter 5 examines that approach.

For the next release, Baodium chose to retain live recommendations with limits on the number of simultaneous calls and the time a product page could spend waiting. That would allow the team to reuse the existing service while testing whether it could meet both the page-latency objective and the product manager’s recommendation-delivery target.

Setting the Concurrency and Time Budgets

The engineers first needed to establish how much additional traffic Recommendation Service could safely admit.

They tested the database demand from existing callers, including the home page and checkout, and established an allocation for product-page lookups. Under the tested conditions, Product Page Service could permit up to 16 concurrent recommendation attempts per instance. The evaluation also included uneven request routing and the loss of a service instance.

Recommendation Service still needed to enforce its own database admission limits. The product-page allocation was a caller-side control, while the receiving service had responsibility for all requests competing for its database connections.

The second limit came from the product page’s latency objective. The engineers measured the time needed to assemble and send the response, then allocated up to 150 milliseconds to optional recommendations.

Listing Listing records those settings.

Caller-side admission and time limits for recommendations.
Python
import threading

REC_CONCURRENCY = 16
REC_TIMEOUT_SECONDS = 0.15
RENDER_RESERVE_SECONDS = 0.05

rec_slots = threading.BoundedSemaphore(REC_CONCURRENCY)

The product-page handler could now treat recommendations as optional content, with a separate function responsible for deciding whether the lookup should be attempted.

Building the product page from required and optional content.
Python
def get_product_page(user_id, product_id, deadline):
    product = catalog_service.fetch(product_id)
    recs = optional_recommendations(user_id, product_id, deadline)
    return build_response(product, recommendations=recs)

The optional function checks whether personalization is enabled for the customer, how much time is available, and whether the instance has capacity for another attempt.

Skipping optional lookups when admission or time limits are reached.
Python
def optional_recommendations(user_id, product_id, deadline):
    if not flags.enabled("product_recommendations", user_id):
        return []

    budget = min(
        REC_TIMEOUT_SECONDS,
        deadline.remaining_seconds() - RENDER_RESERVE_SECONDS,
    )

    if budget <= 0 or not rec_slots.acquire(blocking=False):
        metrics.rec_skipped.inc()
        return []

    try:
        return recommendation_service.get(
            user_id, product_id, timeout=budget)
    except (TimeoutError, ServiceUnavailable):
        metrics.rec_failed.inc()
        return []
    finally:
        rec_slots.release()

Consider what happens when sixteen product-page handlers are already waiting for Recommendation Service. A seventeenth handler does not wait for another semaphore permit. It skips the recommendation call and returns the required product information.3

This is important because permitting every handler to wait for a slot would create another queue inside Product Page Service. The application would then have moved part of the original waiting problem into a different service.

The timeout provides the other protection. If a recommendation request is admitted, the client must enforce the available time budget. A timeout or service-unavailable result causes the handler to return the product without recommendations, while the application records the failed attempt.

The code catches these expected dependency failures and allows other exceptions to reach the application’s normal error handling. A programming error in the recommendation client should still be visible during an investigation.

The finally block releases the local permit whether the call succeeds or the client stops waiting. However, there is an important limitation.

A timeout at Product Page Service does not guarantee that Recommendation Service has stopped processing the request. The receiving service may still be executing a query and using a database connection even after the caller has released its semaphore permit.

The caller-side limit also applies only to one Product Page instance. Twenty instances with sixteen permits each could initiate 320 concurrent recommendation attempts, with additional remote requests potentially continuing after local timeouts.

Recommendation Service therefore needs database admission controls that apply across its callers. Chapter 4 examines deadlines and cancellation, while Chapter 9 develops the concurrency and rate limits needed when several instances share a dependency.

Load Testing and Feature-Flag Rollback

The first rollout had reached only a small fraction of customers. It had not established what would happen when the new feature received the traffic expected at full exposure.

Before releasing it again, the team ran an open-loop load test that scheduled new requests at the expected arrival rate, regardless of whether earlier requests had completed.

This distinction matters during overload. If a test sends another request only after the previous response arrives, a slower service causes the test itself to generate fewer requests. The application may appear to recover because the load generator has reduced the traffic it sends.4

Baodium’s engineers tested the expected peak, uneven traffic distribution between instances, and a scenario in which one instance was unavailable. Under those conditions, product pages met their latency objective, connection acquisition remained below ten milliseconds, and recommendations appeared on 97 percent of eligible, flag-enabled pages.

The team had set a target of 95 percent. The results therefore supported the proposed caller-side limits and the receiving service’s database allocation under the traffic conditions tested.

The release owner approved another staged rollout, this time watching recommendation attempts per instance alongside connection-acquisition latency, product-page response time, and recommendation inclusion.

The engineers also rehearsed disabling the feature flag.

Changing a flag does not stop new requests on an instance that has not received the updated configuration. Requests already in progress may also continue until they finish or time out, and some remote operations may continue beyond the caller’s timeout.

The rehearsal measured how long instances took to stop initiating recommendation calls and how long database demand took to return to its pre-release range.

These measurements gave the release owner an observed recovery interval to use during a future incident. Chapter 10 develops how evidence from tests and production measurements becomes part of a release decision.

Summary

Think back to the feature request that started this chapter. The developer reused an existing service, added a short call to the product-page handler, and verified that the new row appeared correctly. There was nothing particularly unusual about the implementation.

What the team had missed was how often that service would be called once customers began using the feature. Those calls reached a database connection pool shared with other customer operations, and the additional demand began delaying checkout.

The investigation became clearer when the engineers examined connection-acquisition time alongside SQL execution. Once they understood where requests were waiting, they could compare the available designs and agree on limits that protected the required product page while still delivering recommendations to most eligible customers.

We encounter similar decisions when adding an entitlement check to a SaaS application, calling a fraud provider during checkout, or retrieving optional content from another API. Reusing an existing service may be a sensible implementation choice, but the design also needs to account for the requests that service will receive and the resources those requests share with other operations.

Baodium discovered that additional demand during its rollout. In Chapter 2, we will return to the design review and see how the engineers could have estimated much of that demand before deploying the feature.


  1. LaunchDarkly and Unleash are examples of feature-flag systems. Chapter 10 examines how rollout cohorts are selected, how configuration changes reach application instances, and how engineers verify that a flag has been disabled.↩︎

  2. The connection totals in this example represent an instantaneous pool snapshot. The latency measurements summarize a recent observation window. Connection-pool libraries use different metric names, so the labels are illustrative rather than tied to one implementation.↩︎

  3. The code illustrates a synchronous Python handler using threading.BoundedSemaphore. An asynchronous application would use an admission mechanism appropriate to its runtime. The outbound client must enforce the configured time budget across the relevant network operations.↩︎

  4. In k6, the constant-arrival-rate executor schedules iterations independently of response completion. The dropped_iterations metric reports iterations that could not begin as scheduled.↩︎