Modeling Requests, Latency, and Throughput

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

02Chapter 2

Modeling Requests, Latency, and Throughput

Build the payload before the connection is acquired
Chapter 2 figure. Acquisition wait, connection hold, and the work that remains after the query.

After Baodium disabled personalization, the product pages returned to their previous latency range. The incident was over, but the product team still wanted recommendations. At the next design review, the engineers returned to the two proposals raised during the outage. Should they increase the connection pool, or run more Recommendation Service instances?

Both were reasonable ideas. A larger pool might shorten the wait for connections, and additional instances could distribute the incoming requests. The difficulty was that every instance used the same PostgreSQL server. The team had not established how many additional queries that database could process before response times began to deteriorate.

The pool readout from Chapter 1 gave the engineers a starting point. They knew how frequently connections were requested, how long they were used, and how many were available on an affected instance. We can use those measurements to examine the proposals before changing the deployment. The same approach is useful when designing a new service, although we begin with estimates and replace them as testing provides better evidence.

Request Demand at the Dependency Boundary

The first step was to establish which requests reached Recommendation Service. Product pages selected by the feature flag made recommendation calls. The home page and checkout also used the service, so their traffic needed room in the same database allocation.

A customer request does not always produce one database query. A cache hit might avoid the read, while a lookup that performs several SQL statements could acquire a connection more than once. A retry may introduce another attempt without another customer visiting the page. Acquisition attempts show the demand reaching the pool, including requests that time out while waiting. Successful acquisitions and the time those connections are used let us estimate the pool’s average occupancy.

This is a practical distinction when drawing a new request path. We can trace each operation from the API through its dependencies and ask which ones use a scarce resource. It is then possible to estimate the demand at that resource rather than assuming the incoming HTTP request rate describes every component on the diagram.

Concurrency and Connection Occupancy

The number of connections needed depends on how frequently requests use the pool and how long they occupy a connection. Think of a parking garage. Its available spaces depend on how often cars arrive and how long they are parked. The same relationship applies to database connections.

In queueing theory, it is expressed by Little’s Law:1 L=λW.L = \lambda W. Here LL is the average number of operations inside the measured boundary, λ\lambda is their average throughput, and WW is the average time each operation spends there. For the database pool, we measure from the moment a connection is assigned until the application returns it.

During the incident, one Recommendation Service instance processed about 400 lookups per second, with each lookup using a connection for an average of 70 milliseconds. That corresponds to about 28 connections assigned on average, out of the 40 available. Twelve connections might appear to offer plenty of room, yet requests do not arrive evenly, and some database operations take longer than others. A short burst can fill the pool while the average over the full interval still looks acceptable.

The estimate also depends on where we measure. If the lookup rate covers one Recommendation Service instance, its connection occupancy must come from the same instance and workload. A fleet-wide rate gives a fleet-wide estimate, which we would compare with the combined pool allocation and the database’s limits. Figure Figure illustrates why a request, a worker, and a database connection have different measurement intervals.

One request measured three ways. The rate and the duration must describe the same boundary, or the resulting concurrency estimate refers to nothing in particular.
One request measured three ways. The rate and the duration must describe the same boundary, or the resulting concurrency estimate refers to nothing in particular.

Reducing Connection Occupancy

Before changing the number of connections, the engineers considered whether each request could return its connection sooner. A handler sometimes prepares a query payload after acquiring a connection, even when that preparation needs only information from the incoming request.

Preparing a query payload after acquiring a connection.
Python
with pool.acquire() as conn:
    payload = build_payload(request)
    result = query_database(conn, payload)
Preparing the payload before acquiring a connection.
Python
payload = build_payload(request)
with pool.acquire() as conn:
    result = query_database(conn, payload)

Moving that preparation earlier gives other requests access to the connection during the same interval. We would first check that building the payload does not depend on a database read or lock that belongs inside the transaction. After the change, connection-occupancy measurements can show whether it made a meaningful difference. Neither the database nor the number of instances has changed, yet the service may now accommodate more requests.

Fleet-Wide Connection Budgets

The next proposal was to add Recommendation Service instances. That could spread CPU and application processing across more machines, although the new instances would also create their own database pools.

Suppose the fleet has 20 instances, each configured for a maximum of 40 connections. Together they could open 800 PostgreSQL sessions. If the database team allocates only 600 sessions to Recommendation Service, that configuration already permits more connections than its allocation. A rolling deployment can temporarily add instances while the older ones are still serving requests, increasing the possible session demand again. 2

We can use the deployment plan to establish an initial ceiling. If the 20-instance fleet can temporarily run 21 instances, limiting each pool to 28 connections would permit at most 588 sessions. That fits inside the 600-session allocation, although the remaining allowance may be too small for maintenance or recovery, and it tells us little about query throughput. The actual pool settings still need to be tested with the application’s traffic and the database’s other responsibilities.

The team also considered PgBouncer, which can allow many application clients to share a smaller number of PostgreSQL sessions. Transaction pooling is useful when server sessions are the constraint, but it comes with compatibility requirements for applications that depend on session state. It also leaves the queries competing for the same database CPU, memory, and storage resources. We would test it against the actual application before using it to support a larger fleet.

Testing Sustainable Admission Rates

A capacity estimate helps the engineers choose a configuration to test. They still need to see what happens when requests overlap, traffic arrives in bursts, and a service instance becomes unavailable. As Chapter 1 explained, an open-loop test continues scheduling new requests at the configured arrival rate while earlier requests are still running.

Table Table shows illustrative results from one Recommendation Service instance with a 40-connection pool. Each stage runs long enough to assess whether unfinished requests are accumulating.

Illustrative steady-state load-test stages for one instance. Unfinished requests must also be checked at each stage.
Offered/s Completed/s Rejected/s Acquire p95
300 300 0 2 ms
400 400 0 8 ms
480 470 10 25 ms
560 440 120 80 ms

At 400 offered requests per second, the instance completed every request in the test interval, without reported rejections. At 480, it completed 470 and rejected 10 per second. Increasing the offered rate to 560 then produced fewer completions and many more rejections. The bend where additional demand stops improving completed throughput is often called the throughput knee. We still need database measurements to understand which resource causes the slowdown.

For this release, the team required connection-acquisition p95 to remain below 50 ms and rejections below one percent of offered requests. The 400-request stage passed both conditions. The 480-request stage met the acquisition threshold, but its rejection rate was about 2.1 percent. That stage therefore failed the release gate, even though its acquisition time looked acceptable on its own.

The engineers tested intermediate rates and repeated the evaluation with one instance unavailable and with deployment overlap. Those tests could establish the upper range for admission at Recommendation Service. The 16-permit limit in Chapter 1 was a separate caller-side allocation. Choosing it also required the home-page and checkout demand, the number of Product Page instances, and the possibility that remote operations continued after caller timeouts. The load-test table alone could not establish that setting.

The measurements also help us compare corrections. If the database has unused query capacity, a larger pool may reduce acquisition waits. If transactions are waiting on locks or consuming too many database resources, more connections may increase latency. Repeated reads may justify caching, while an operation that customers can finish later may be better handled through a durable queue. Those choices return in Chapters 5 and 12.

Design Exercise: Photo Upload Admission and Durability

We have production measurements for Baodium, but an architecture review may begin before an application has received any traffic. Consider a photo-sharing service that expects 300 uploads per second during its evening peak. The first design writes an image to object storage and a metadata row to PostgreSQL. Each metadata write is estimated to occupy a connection for 20 milliseconds. Six application instances serve uploads, and the database team has allocated 60 sessions to the service.

How many connections should each instance be permitted to open, and which failure conditions would we need to test before approving the first release? We can start with the same relationship used for Recommendation Service, then examine what the application promises when a customer uploads a photo.

Connection Allocation During Deployments and Failures

At the estimated peak, the metadata writes would use about six database connections on average across the fleet. That gives us a starting point, although the allocation must also permit bursts and database operations that last longer than expected.

During a rolling deployment with one surge instance, seven application pools could run concurrently. An eight-connection limit per instance allows at most 56 sessions, within the service’s allocation of 60. With one instance unavailable, five surviving instances would receive the upload traffic. Each would have to process a larger share, so the load test needs to include that condition rather than relying on the original average.

We would test the evening peak, uneven routing, one unavailable instance, and the rolling deployment. The results would tell us whether the proposed pools and PostgreSQL allocation can support the actual transactions. The estimate is not enough to establish the sustainable upload rate.

The Upload Acceptance Contract

Now suppose the product team wants the upload screen to confirm that the image bytes reached object storage without waiting for the photo to appear in the feed. That changes the response contract. What can the application tell the customer after storing the image while its metadata is still pending?

One design begins with POST /uploads. The application records a pending upload operation with a stable identifier and returns that identifier along with a short-lived object-storage upload URL. The client sends the image directly to object storage. After the bytes are accepted, a completion request or storage notification starts metadata processing. Until the metadata is committed, the upload status remains pending, and the client can retrieve that status using the original identifier.

Suppose the object is stored successfully but the completion notification never reaches the worker. A recovery process can examine pending upload operations, check whether their objects exist, and resume processing or apply the expiration policy. The interface can acknowledge that the bytes were uploaded while continuing to show the photo as processing. It should report the photo as ready only after the metadata is committed and the required processing has completed.

This revised workflow also changes database demand. The first estimate covered one metadata write per upload. Recording the pending operation and later updating its status introduce additional transactions, so we would revisit the pool estimate and test the new request path. The capacity model is still useful, but the API contract determines which operations the system must record and recover. Chapter 3 examines how those identities and records prevent an interrupted operation from being repeated incorrectly.

Summary

By the end of the review, Baodium’s engineers could compare the proposed changes against a shared database allocation. More application instances could distribute incoming requests, while smaller pools and shorter connection occupancy could reduce pressure on PostgreSQL. The load test then established how much of that traffic the service could accept before requests began to wait or get rejected.

The photo-upload design introduced a related decision. Before selecting how requests will be processed, we need to agree on what the application means when it reports that an operation has been accepted. If the client loses its connection after sending a payment or starting an upload, the server may already have recorded part of the result. Chapter 3 follows that uncertainty into durable operation identities, state transitions, and recovery.


  1. J. D. C. Little, “A Proof for the Queuing Formula: L=λWL=\lambda W,” Operations Research, 1961. The relationship describes long-run averages for a stable system.↩︎

  2. A Kubernetes Deployment can temporarily run more pods than its desired replica total when maxSurge permits it. Chapter 10 examines how this affects a release’s resource allocation.↩︎