DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Adding Graph Retrieval to a RAG Pipeline With Python
  • Architecting for <1s Latency: Managing Eventual Consistency in Distributed Search Platforms
  • Microservices Architecture in Production: 7 Engineering Decisions That Determine Success or Failure
  • The Bill You Didn't See Coming

Trending

  • Detecting and Measuring Bias in Training Data Before It Reaches Production
  • Function Calling: Responses API vs Chat Completions
  • Bolting an LLM Onto a System That Can't Afford to Be Wrong
  • Using LLMs to Generate Unit Tests and Review Pull Requests in Spring Boot

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Performance
  4. The Query Takes 20 ms. Why Does the API Take Two Seconds?

The Query Takes 20 ms. Why Does the API Take Two Seconds?

A 20ms database query can still result in a two-second API response. This article explores the causes of extra latency and how developers can identify and fix them.

By 
Samuel Ogbonna
·
Dec. 03, 26 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
1 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

A developer notices that an API endpoint takes almost two seconds to respond. The first suspect is the database, so the team checks the query logs, reviews the execution plan, and looks for anything that might explain the delay.

The query finishes in 20 milliseconds. Database CPU usage is normal, and nothing in the monitoring dashboard suggests a serious problem.

Yet users are still waiting two seconds for a response.

It's easy for investigations like this to become focused on the database, especially when an endpoint spends much of its time retrieving information. But a fast query tells us very little about what happens before the database receives it or after the results return.

To find the delay, we need to follow the request through the application and understand where those missing milliseconds are going.

The Missing 1,980 Milliseconds

An API request passes through multiple stages, adding delays beyond database query execution.Figure 1. An API request passes through multiple stages, adding delays beyond database query execution. 

Consider an API endpoint that retrieves a customer's recent orders. The database executes the main query in 20ms, but the entire request takes 2,000ms.

That leaves 1,980ms to account for.

The first thing to check is where each measurement begins and ends. Database execution time usually describes the work performed by the database engine. The application has other responsibilities, including receiving the request, obtaining a database connection, processing the returned data, and preparing a response.

Depending on how monitoring is configured, some of these operations may not appear in the database logs at all.

This matters when engineers start optimizing the SQL statement. Suppose they reduce execution time from 20ms to 10ms. They've improved query performance by 50%, but the overall response time would drop by only 10ms if everything else stayed the same.

The user may barely notice the difference.

Before changing anything, I'd want to know how much time the request spends at each stage. Even a basic breakdown can prevent hours of work on the wrong problem.

Where Requests Wait Before Reaching the Database

One place worth investigating is the database connection pool.

Most applications reuse a limited number of database connections rather than opening a new connection for every request. This reduces connection overhead, but it also creates a shared resource that requests may have to wait for.

Imagine an application with ten available connections. All ten are occupied when another request arrives. That request must wait until a connection becomes available. Once it gets one, the database might complete the query in 20ms, even though the application spent several hundred milliseconds waiting beforehand.

This behavior is documented in HikariCP's configuration guide. When the pool reaches its configured maximum, and no idle connections remain, a request for a connection can block until one becomes available or the connection timeout is reached.

A common reaction is to increase the pool size. Sometimes that helps, but I'd first investigate why connections are staying occupied.

For example, an application might hold a database connection while waiting for an external service. Under heavy traffic, several slow operations can leave other requests waiting unnecessarily. Worker threads can cause similar problems: if all available workers are busy, incoming requests may spend time in a queue before processing begins.

Connection acquisition time, pool utilization, and request queue length can help distinguish these problems from slow database execution.

When Fast Queries Add Up to a Slow Request

Another possibility is that the endpoint executes far more queries than expected. Imagine an API that retrieves 50 customer orders. The initial query finishes in 20ms. The application then retrieves the items associated with each order through separate database queries.

This is commonly called the N+1 query problem. If those 50 additional queries each take 15ms and execute sequentially, they add 750ms to the request. Every query may appear fast in isolation, but the total cost becomes significant when the application makes so many database round trips.

The problem becomes easier to identify when engineers examine the number of queries executed during a single request, rather than looking only at individual query durations. The application may also spend considerable time preparing the response. Converting database records into JSON requires processing, and the cost can grow when the response contains large amounts of data.

Then there are external services. An order-history endpoint might contact a delivery provider to retrieve shipment information. If that service takes 500ms to respond and the application waits for it synchronously, that delay becomes part of the user's request time.

By this point, it's easy to see how an API can take two seconds to respond without any individual SQL statement being particularly slow.

Finding the Actual Bottleneck

Distributed tracing reveals where time is spent across database operations, application processing, and external services.

Figure 2. Distributed tracing reveals where time is spent across database operations, application processing, and external services.

The challenge is collecting enough information to identify where the time is going.

This is where distributed tracing becomes useful. Rather than showing only the total duration of a request, tracing records its journey through instrumented components and operations. OpenTelemetry provides a framework for collecting traces, metrics, and logs. With suitable instrumentation, engineers can examine database calls, outgoing HTTP requests, and application operations in the context of the same request.

Consider a hypothetical trace for our two-second endpoint:

request stage elapsed time

Waiting for a database connection

400ms

Database operations, including repeated queries

800ms

Waiting for an external service

500ms

Other application processing and overhead

300ms

Total response time

2,000ms


These figures are illustrative. They represent separate, non-overlapping portions of the request's elapsed time, not measurements from a real application. Actual traces may contain nested or overlapping spans, so their durations cannot always be added together.

The example nevertheless shows why the 20ms query isn't necessarily the right place to start optimizing. The investigation needs to account for the entire request, including time spent waiting for shared resources and external dependencies. I'd also compare requests made during quiet periods with those made during peak traffic. If connection wait times rise sharply under load, that suggests a different problem from an endpoint that remains slow even when traffic is low.

Average response times can hide what some users experience, too. Looking at the 95th and 99th percentile latency helps reveal requests that take unusually long to complete, even when most requests are fast. The aim is to understand the path taken by slow requests instead of relying on a dashboard that summarizes everything into one number.

Fixing the Delay Without Guesswork

Once the team knows where the time is being spent, the next decision becomes easier.

If requests are waiting too long for database connections, I'd examine how connections are used and released. Long-running transactions, unnecessary connection holding, and excessive concurrency deserve attention before pool settings are changed. If repeated queries account for most of the delay, fetching related records together may reduce the number of database round trips. The team should then measure the result to make sure the change improves the complete request rather than just an individual query.

Where external API calls are responsible, the team can review timeouts, cache suitable information, or run independent operations concurrently. Each option has trade-offs. Caching introduces freshness concerns, while increasing concurrency may improve an individual request but put additional pressure on the database or another shared service.

The same principle applies to response serialization and application processing. If profiling shows that preparing a large response consumes significant time, reducing unnecessary fields or processing fewer records may help more than changing the database query.

Whatever the suspected cause, I'd avoid judging a change solely by how it performs in a quick local test.

Run the same representative workload before and after the improvement. Compare overall API response time, including slower requests, and check whether error rates or resource usage have changed. Where possible, keep the workload and test conditions consistent so the results are meaningful. A useful performance fix should produce a measurable improvement under conditions that resemble actual usage.

Conclusion

When a database query takes 20ms, and the API takes two seconds, the investigation shouldn't end with the query plan. There's still a considerable amount of application activity to examine. Requests may wait for connections, trigger dozens of additional queries, spend time processing large responses, or depend on external services that respond slowly.

For me, the most useful starting point is understanding the complete request before deciding what needs optimization. It helps engineers avoid spending time improving a component that was already performing well. A fast database query is encouraging. The real improvement comes when the application delivers that speed to the user.

API Database Performance

Opinions expressed by DZone contributors are their own.

Related

  • Adding Graph Retrieval to a RAG Pipeline With Python
  • Architecting for <1s Latency: Managing Eventual Consistency in Distributed Search Platforms
  • Microservices Architecture in Production: 7 Engineering Decisions That Determine Success or Failure
  • The Bill You Didn't See Coming

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook