BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
Backend Engineering

Expert · Lesson 10 of 12

Software Architecture

Find a Tail Latency Regression

Checkout barely moves at the median, but its p99 triples. Trace a missing 610 milliseconds, shorten a connection hold and decide whether to roll out the fix.

A shopkeeper holds a blue notebook beside a payment terminal as shoppers wait at the counter.

At a stationery shop in Sharjah, most customers get an order number before they have time to put down their phones. A few stare at the checkout button for a full second. The complaints started with the release that added a delivery quote. The dashboard still says “median 120 ms.” Should the engineer roll back the quote feature, buy more database connections, or change the order in which checkout does its work?

We will investigate a worked example with illustrative measurements. Our unit of observation is one checkout attempt, timed at the gateway from arrival until the final response. We will keep the delivery quote, reproduce the change in latency, and test a proposed fix under the same demand. The investigation ends with a release decision. Improving a single attractive trace will earn us a hypothesis, but it will take a distribution of comparable observations to justify that decision.

Define the population before looking for a culprit

Take two windows of 10,000 attempts each. Both have the same mixture of pickup and delivery, basket sizes, branch traffic, database size and worker count. Within each window, sort the elapsed times from smallest to largest. Using the nearest-rank convention, p50 is observation 5,000 and p99 is observation 9,900. A p99 of 940 ms means the observation at that rank took 940 ms. It says nothing about how far beyond that point the slowest customer waited. Counting actual threshold violations answers a different, often more practical question.

Checkout measurement Previous release Release with delivery quotes Candidate fix
Completed attempts 10,000 10,000 10,000
Median 118 ms 120 ms 121 ms
p99 310 ms 940 ms 360 ms
Attempts over 500 ms 34 260 48
Errors or timeouts 0 0 0

In this fixture all attempts complete successfully, so the counts are easy to reconcile. The new release puts 2.6 percent of attempts over half a second, up from 0.34 percent. That is 226 additional slow checkouts in the same volume while the midpoint moves only two milliseconds. In a live investigation count failures, timeouts and abandoned attempts separately and retain their observed duration where available. Fast rejection of overloaded requests could otherwise make the latency of successful requests look better while fewer people complete a purchase.

Decide how percentiles are computed across instances. For raw observations you can pool the durations. For a classic Prometheus histogram, aggregate compatible bucket counts across replicas over the same interval before estimating the percentile. The estimate depends on bucket boundaries and interpolation. A bucket at the exact 500 ms objective also lets you count observations at or below that threshold without interpolating. Averaging each instance's reported p99 gives a quiet worker the same influence as one that served half the shop. Prometheus guidance on histograms and summaries

Read the clock on one slow checkout

Select a delivery request near the affected tail and a pickup request handled by the same application instance in the same minute. Also select a fast delivery request. The three-way comparison separates “uses delivery” from “is slow.” In our slow delivery trace, order SH-614 takes 940 ms. Its nonoverlapping intervals are 40 ms in routing and input validation, 610 ms waiting to acquire a database connection, 210 ms obtaining a quote, 60 ms executing the transaction and 20 ms preparing the response. Those five intervals sum to 940 ms.

The 610 ms gap changes the investigation. The database has no SQL statement lasting anything like that long. A query timer starts only after the application has a connection. If the trace starts at the first query, the missing time looks like general application slowness. Add a span around acquisition and record how long the connection stays checked out. Keep the order reference in a suitably protected trace when needed for diagnosis, and use bounded attributes such as release, route and fulfillment type for metrics. OpenTelemetry's trace and span model

Do not add a parent span to its children or sum parallel calls to explain wall time. The connection-hold interval overlaps the quote call in this release. Adding both would count the same 210 ms twice. Draw their start and end times on the same request timeline instead. The code takes a connection, makes a network call while still holding it, writes the order and returns the connection. Other checkouts queue behind a resource that is idle from the database's perspective. Some of those waiting checkouts pick up in store and never need a quote themselves.

Turn that trace into a prediction

The pool has eight connections per instance. During a burst, eight delivery requests can acquire all eight and then wait on the quote service. A ninth checkout cannot begin its short database operation until one of the eight releases its connection. The fast delivery comparison shows a prompt quote and little waiting. The slow pickup comparison shows a long acquisition wait with no quote span. Across the affected window the number of waiting callers rises when all eight connections are checked out, while database CPU stays close to its previous level.

Write down a prediction that could fail. If holding connections across quote calls drives the regression, moving that call outside the hold interval should sharply reduce acquisition waits at comparable arrival rates. The quote itself might remain just as slow. If waits persist after the hold time falls, examine another consumer of the same pool or a different bottleneck. Merely increasing the pool from eight to eighty would change the experiment and might move contention to the database. It would give little evidence about which code path caused the new demand.

Change one behavior. Ask for the quote before taking a connection for the checkout transaction. Bind the quote to the branch, basket revision, amount and validity period. Inside the transaction recheck the inputs that determine eligibility and stock. A changed basket or an expired quote must cause the service to obtain a valid decision or return a clear retry outcome. Preserve the existing checkout request key so a lost response cannot create two orders. Time saved by skipping a correctness check would not qualify as a successful performance fix.

Keep the pressure on during the comparison

For each run, replay the same arrival schedule over 500 seconds, averaging twenty starts per second with identical short bursts. Warm the application and restore equivalent test data before measuring. Use isolated order identities and a quote-service fixture that reproduces the same latency pattern for the same inputs. Check that the load generator actually starts all 10,000 attempts on time and that the last outstanding attempts are allowed to finish. Report offered traffic, starts, completions and errors alongside latency so a queue growing outside your measurement cannot masquerade as improvement.

A fixed set of simulated customers that waits for each response before starting another checkout will send fewer requests when the service slows down. That behavior is realistic for some journeys. Here it would remove pressure exactly when we need to compare contention under equal demand. An open arrival model schedules new attempts independently of earlier completion. Give the generator enough capacity and inspect dropped iterations. The model alone cannot guarantee the requested traffic reached the gateway. Grafana k6 on open and closed load models

With the candidate in place, the median is 121 ms, p99 falls to 360 ms, and 48 attempts exceed the 500 ms threshold. The tail improved substantially while the median barely moved. Compare representative slow traces again. One 360 ms delivery spends 40 ms on input, 205 ms obtaining the quote, 15 ms waiting for a connection, 75 ms in the transaction and 25 ms returning the response. Most of this customer's wait is now in the quote service. Its 205 ms duration is close to the earlier 210 ms. Its greater share of the remaining total does not establish that the provider got slower.

Decide what to ship and what to watch

Before the test, the shop set its release gate at fewer than one percent of attempts above 500 ms, no extra failures, and no duplicate orders or invalid quotes in the replay. The candidate's 48 out of 10,000 is 0.48 percent. Check the committed orders against the test inputs and explicitly exercise quote expiry and a concurrent basket edit. If the correctness checks pass and repeated matched windows reproduce the improvement, the evidence supports a limited rollout. It does not establish a return to the old p99 of 310 ms or remove the need to measure live behavior.

During rollout compare like branches and fulfillment types at similar traffic. Watch gateway p99, the threshold count, errors, acquisition waits, quote duration and attempted versus completed purchases. Keep enough ordinary traces to compare with slow ones. Sampling only the slowest traces is excellent for explaining individual failures and a poor way to estimate how often they occur. If acquisition waits remain low but delivery customers still miss the objective, the next experiment should isolate quote latency. If pickup customers remain slow as well, inspect a shared stage first.

اقرأ الدرس بالعربية

Exercise: would you expand the rollout?

A second branch reports a 340 ms p99 and only 30 completed checkouts above 500 ms. Its generator scheduled 10,000 starts, dropped 700 and completed 9,300. Its database pool looks healthy. Does that justify expanding the rollout?

Answer. Hold expansion until the branch completes a comparable test. The 30 slow checkouts describe the workload that actually arrived. The missing seven percent could remove the bursts that exposed the original contention. Inspect generator capacity and gateway arrivals, replay the complete schedule, and compare the same thresholds and correctness checks. Expand if the full-load result clears the agreed gate and traces show that shorter connection holds explain the improvement. A lower percentile on a materially lighter workload cannot answer the release question.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.