smaple.tr
Backend & APIs

Performance Engineering: From a Latency Target to a Regression Test

Mehmet Kurtipek
November 16, 2025
16 min read
Backend & APIs
Performance engineering
Profiling
Load testing
Observability

Performance engineering is the work of making a system meet measurable speed and capacity targets, and keep meeting them as the code and the traffic grow. In practice it is a loop: pick a target a user would notice (say, 95% of searches answer in under 300 ms), measure the real system against it, find the bottleneck with traces and profilers, fix that one thing, prove the fix under realistic load, and add a check so it can't quietly come back. The load test people run before a release is one step of that loop.

A small team can run that loop without a dedicated performance engineer. What usually goes wrong is a skipped step: someone reads the code, guesses where it's slow and speeds up the wrong thing, or fixes the right thing once and never checks it again.

Performance engineering vs performance testing

A load test answers one question: how does this build behave under this traffic? That is useful, and it comes late. By the time you run it, the data model, the number of calls each request makes and the decision to do work synchronously are already in the code, and changing them a week before launch is expensive.

Performance engineering starts earlier and ends later. It sets targets during design, shapes the architecture around them, checks them in CI and watches them in production, where regressions often show up first.

Start with a target someone would notice

A useful target has three parts: an operation a user or the business cares about, a percentile and a threshold. "The API should be fast" has none of them. "99% of search requests return in under 500 ms, measured at the load balancer over 28 days" has all three. Write targets like that as service level objectives (SLOs). If a contract promises them to a customer with penalties attached, it has become an SLA, which our post on SLA management covers.

For targets, use percentiles, never averages. Google's SRE book shows a service where a typical request takes about 50 ms while 5% of requests are 20 times slower, and points out that an alert on average latency would see no change over the day even as the tail moves (Site Reliability Engineering, chapter 4). The median describes the typical user. The p95 and p99 describe the users who complain.

Two properties of percentiles catch people out:

  • They don't add up. If the database's p95 is 40 ms and the application's p95 is 60 ms, the request's p95 is not 100 ms. Per-component budgets are fine for planning, but measure the end-to-end number on its own.
  • Fan-out amplifies the tail. In "The Tail at Scale", Jeff Dean and Luiz Barroso take a server that usually answers in 10 ms but has a p99 of one second. A user request that has to wait for 100 such servers in parallel takes more than a second 63% of the time (Communications of the ACM, 2013). A page that calls ten microservices has the same problem at a smaller scale.

For web pages, Google has already picked the targets. Core Web Vitals ask for Largest Contentful Paint within 2.5 seconds, Interaction to Next Paint (INP) of 200 ms or less and Cumulative Layout Shift of 0.1 or less, measured at the 75th percentile of page loads and split by mobile and desktop (web.dev).

Not every target is a response time. EdgeHunters, a Dublin company, sells betting-analytics tools, and we built and ran its odds-data platform for about two and a half years. In a product like that a stale price makes a recommendation worthless, so the speed that matters is freshness: how old a price is when the user sees it. The platform packaged the latest odds every five minutes for the product to read. In 2025 we also designed the next step to cut end-to-end latency: a streaming, event-driven architecture for pairing the same game across sportsbooks. Throughput (documents an hour, jobs a minute) and cost per request can be targets in the same way.

Measure the real system before changing anything

Lab and field numbers often disagree, and users live in the field. Lighthouse loads a page in a simulated environment with no user, so it cannot measure INP at all; the Total Blocking Time it reports is a lab stand-in. For the real figures you need real-user monitoring (RUM) or Chrome's field data. This matters most when your users are on phones. On a property-search platform we build for a client in Finland, most Google clicks in September 2026 came from mobile devices, so a Lighthouse run on a developer's laptop says little about the visits that matter.

On the backend, three signals cover most investigations:

  • latency histograms per endpoint, so you can read p50, p95 and p99 instead of an average;
  • request rate and error rate next to them, because latency that drops while errors climb is not an improvement;
  • distributed traces, which show how one slow request spent its time across services, queries and outbound calls. OpenTelemetry is the vendor-neutral way to produce them, and the major APM products accept its data.

Keep personal data out of span attributes and logged URLs. A trace that records an email address or an ID number in a query string makes your monitoring vendor a processor of that data, with all the paperwork that implies.

Find the bottleneck before touching code

Start from the trace of a slow request. It tells you which span is wide, and the code you suspect can wait until the trace points at it. Then pick the tool for that layer.

If the time goes to the database

On PostgreSQL, turn on pg_stat_statements and sort by total time. A 3 ms query called two million times a day costs the database 100 minutes; a 4-second report run twice costs it eight seconds. Sorting by mean time would put the report first.

-- Needs shared_preload_libraries = 'pg_stat_statements' in postgresql.conf
-- (changing it needs a server restart) and
-- CREATE EXTENSION pg_stat_statements; in the database you query.
SELECT left(query, 80)                    AS query,
       calls,
       round(total_exec_time)             AS total_ms,
       round(mean_exec_time::numeric, 2)  AS mean_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

The setup and column names are in the PostgreSQL documentation. Take the top entries to EXPLAIN ANALYZE, which runs the query and shows the actual row counts and time for every node of the plan. Since PostgreSQL 18 it also reports buffer usage by default. Because it really executes the statement, wrap an UPDATE or DELETE in a transaction and roll it back.

If the time goes to your code

Use a sampling profiler on the real workload, in production or in an environment with production-sized data. The hot path on a laptop with ten rows in the database is usually a different hot path.

  • Python: py-spy attaches to a running process without a restart and writes a flame graph. On Linux, attaching to a process it didn't start needs root, and inside a container the SYS_PTRACE capability.
  • JVM: async-profiler, or JDK Flight Recorder, which ships with the JDK.
  • Go: pprof, exposed over HTTP by the standard library's net/http/pprof.
  • Node.js: node --cpu-prof writes a .cpuprofile file that Chrome DevTools can open.

In a flame graph, width is time. Look for the widest frames that belong to your own code, and keep in mind what each one can give back: a function that takes 8% of a request can save you 8% at most, however clever the fix.

If nothing looks wide

When no span or frame stands out, the request is usually waiting: on a lock, a connection pool, a thread pool, a disk or another service. CPU profilers don't show time spent waiting. Brendan Gregg's USE method is a good checklist here: for every resource, check utilization, saturation and errors. A connection pool at full utilization with requests queuing for a connection looks, from the outside, exactly like a slow database.

The usual fixes, and what each one costs

Slow web backends tend to be slow for a short list of reasons. None of the fixes is free.

N+1 queries

A list endpoint loads 50 orders, then runs one query per order to fetch its customer: 51 round trips where two would do. ORMs make this easy to write and hard to see. The fix is a join or a batched load (select_related and prefetch_related in Django, DataLoader in a GraphQL server). Then lock the fix in with a test that fails if the query count grows with the data:

from django.test import TestCase
from django.urls import reverse

from orders.tests.factories import OrderFactory  # your own factory_boy fixtures


class OrderListQueries(TestCase):
    def test_query_count_does_not_grow_with_rows(self):
        OrderFactory.create_batch(25)
        # The view uses select_related("customer").prefetch_related("items"):
        # one query for orders joined to customers, one for all their items.
        with self.assertNumQueries(2):
            response = self.client.get(reverse("order-list"))
        self.assertEqual(response.status_code, 200)

The exact number depends on your view, since sessions and pagination add queries of their own. What matters is that it stays the same with 25 orders as with 5. The status check is there so a redirect to the login page or a 404 can't pass for a fast endpoint. The cost: eager loading pulls in data some callers don't need, so apply it per endpoint and leave the model's default alone.

Missing or wrong indexes

A sequential scan of a large table under a selective WHERE in the EXPLAIN ANALYZE output is the classic sign. A multicolumn B-tree index helps most when the query filters on its leading columns, so column order matters. Every index slows writes and takes disk, so add the ones your top queries need and check pg_stat_user_indexes for indexes nothing ever scans.

Connection pools that are too big

More connections feel like more capacity, but past a point they only add contention inside the database. The PostgreSQL project's starting formula, popularised by HikariCP's About Pool Sizing page, is connections = (core_count × 2) + effective_spindle_count: physical cores on the database server (hyperthreads don't count), plus a spindle count that is zero when the working set fits in cache. The same page admits nobody has analysed how the formula behaves on SSDs and tells you to load-test around it. Two more checks: the database sees the total across all application instances, so ten pods with a pool of 20 can open 200 connections; and Little's law gives you the demand side, because 500 queries a second that each hold a connection for 10 ms keep about five connections busy.

Calls in series that could run in parallel, or not at all

A request that calls three services one after another pays the sum of their latencies; calling them concurrently pays roughly the slowest. Work that doesn't change the response, such as sending an email, updating a search index or writing an audit record, belongs on a queue. Every outbound call needs a timeout, or one slow dependency ties up your workers and connections until everything queues behind it.

For tail latency in fan-out systems, Dean and Barroso describe hedged requests: if a replica hasn't answered after a short delay, send the same request to a second one and use whichever answers first. In their BigTable benchmark, hedging after 10 ms cut the 99.9th-percentile latency of reading 1,000 keys from 1,800 ms to 74 ms, at the price of 2% more requests. It is only safe for idempotent reads, so never hedge a payment or any other write.

Caching

A cache pays off when the same data is read far more often than it changes and a slightly stale answer is acceptable. You pay for it in invalidation logic, in a new failure mode (the cache is empty after a deploy and the database takes the full load at once) and in bugs where users see old data. Decide how stale is acceptable before you pick a TTL. Our Redis guide goes through the patterns.

Too much JavaScript

On the frontend the scarce resource is the user's phone. A large bundle hurts INP because the main thread is busy parsing and running code when the user taps. Split by route, defer what the first view doesn't need, and set a bundle-size budget in CI so the bundle can't double without anyone noticing.

Load test the fix, with honest traffic

The easiest way to spoil a load test is the traffic model. In a closed model, a fixed number of virtual users each send a request, wait for the answer and send the next. When the system slows down, those users wait longer and send fewer requests, so the load falls exactly when it should hurt. The k6 documentation notes that this problem is known as coordinated omission. Real users keep arriving however slow your server is, so use an open model, where you set the arrival rate (k6: open and closed models).

// search-load.js
// Run with: k6 run -e BASE_URL=https://staging.example.com search-load.js
import http from 'k6/http';
import { check } from 'k6';

export const options = {
  scenarios: {
    search: {
      executor: 'constant-arrival-rate', // open model: arrivals don't wait for responses
      rate: 50,                          // 50 new searches...
      timeUnit: '1s',                    // ...every second
      duration: '10m',
      preAllocatedVUs: 100,
      maxVUs: 500,
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<300', 'p(99)<800'],
    http_req_failed: ['rate<0.01'],
  },
};

export default function () {
  const res = http.get(`${__ENV.BASE_URL}/api/search?city=helsinki&page=1`);
  check(res, { 'status is 200': (r) => r.status === 200 });
}

If a threshold fails, k6 exits with a non-zero code, so the same script can fail a CI job. Watch the dropped_iterations metric in the summary. Drops at the start of a run usually mean k6 needs more VUs; drops that appear later mean requests are taking longer and the system under test is degrading.

Other ways a load test misleads you:

  • Test data that is too small. A query that is instant on 10,000 rows can scan for seconds on 50 million. Test against production-sized, anonymised data.
  • Only warm caches. Run once from cold, as right after a deploy, as well as warm.
  • Runs that are too short. Ten minutes won't show a memory leak or a disk filling with logs; a soak test of several hours will.
  • Other people's limits. Your capacity includes the quotas of every API you call. In the field-ticket automation we built with an automation agency partner for an oilfield-services company, about 100 documents a day go through LLM extraction, and most of what broke was the LLM APIs' rate limits (HTTP 429). The fix was falling back to alternative models when a call hit the limit. Find those quotas before your peak day, and never point a load test at someone else's production API without permission.

Capacity planning comes out of the same tooling. Raise the arrival rate step by step until the p99 threshold breaks. The last rate that passed is your current ceiling, and the gap between it and your expected peak is your headroom. The expected peak usually comes from the calendar: a sale, a product launch, the hour exam results are published. Size the test for that day.

Keep regressions out

Fixes decay. Someone adds a field to a serializer, and the endpoint fixed in March is doing N+1 again by June. Cheap guards catch most of it:

  1. Query-count tests like the one above on your busiest endpoints.
  2. A short k6 run with thresholds against staging, nightly or on every merge to main. Our GitHub Actions guide shows how to wire up a job like that.
  3. Lighthouse CI for lab metrics (LCP, CLS, and TBT in place of INP), plus a bundle-size budget.
  4. In production, a comparison of p95 and p99 per endpoint before and after every deploy, and alerts on SLO burn rate instead of on individual slow requests.

When it isn't worth it

Performance work costs engineering time, and sometimes the honest answer is to skip it. An internal tool five people use, a nightly batch that finishes hours before anyone needs its output, or a product still looking for its first users rarely justify a week of tuning. If the problem really is capacity, a bigger database instance can cost less per month than that week of an engineer's time.

Hardware won't fix an N+1 loop that grows with every new customer, lock contention, or tail latency from fan-out, and scaling out often makes those worse. If you do scale up, keep an eye on the bill; our post on cloud cost optimization covers how to stop it from becoming the next problem.

Frequently asked questions

What does a performance engineer do?

They define and track performance targets, profile slow paths, design and run load and stress tests, and work with developers on the fixes. Job ads use the title loosely, so read the duties: some want a load-testing specialist, others someone who profiles production code and redesigns hot paths. In a small team it is usually a hat a senior backend engineer wears.

What is the difference between load, stress and soak testing?

A load test runs the traffic you expect, peak included, and checks it against your targets. A stress test keeps raising the load past that point to find where the system breaks and how it breaks: whether it slows down gradually or starts failing requests and needs a restart to recover. A soak test holds normal load for hours to catch what only builds up over time, such as a memory leak or a disk filling with logs. In k6 they are the same script with a different scenario.

When should performance work start?

At design time, for the decisions that are expensive to change later: how many services one request touches, what runs synchronously, how lists are paginated. Tuning individual functions can wait until a profiler points at them.

Is performance engineering the same as SRE?

They overlap. Site reliability engineering owns reliability in production, latency SLOs included. Performance engineering also covers design decisions and testing before release. In small teams the same people do both.

If a slow backend is what brought you here, you can tell us about it through our backend and API services page.

Related Articles

August 1, 2026

Kong vs Traefik vs AWS API Gateway: How to Choose

Kong, Traefik and AWS API Gateway compared as of October 2026: features, licensing, Kubernetes support and what AWS charges for 100 million requests a month.

Read More: Kong vs Traefik vs AWS API Gateway: How to Choose
July 4, 2026

gRPC vs REST for Microservices: When gRPC Is Worth It

When gRPC beats REST between services, what it adds to your operations (load balancing, deadlines, browser access), and what our own protobuf vs JSON test showed.

Read More: gRPC vs REST for Microservices: When gRPC Is Worth It
March 14, 2026

RPA Implementation: From Process Choice to Bots That Keep Running

Most of an RPA implementation is choosing the process and designing for exceptions. The order we work in, current license prices, and what broke in the n8n and LLM automation we built with an agency.

Read More: RPA Implementation: From Process Choice to Bots That Keep Running