DEV Community

The Creative CodeFlow
The Creative CodeFlow

Posted on

Your API Can Be Slow Even When Your Code Is Fast

You optimized your function.
It runs in 5ms.
But your API still takes 2 seconds.
Why?
Because your function isn't the only thing your API is doing.
A request might look like this:
Client
↓
API
↓
Database
↓
External API
↓
Response

Your code could be extremely fast while the database or external service is slow.
For example:
const user = await getUserFromDatabase();
const weather = await getWeatherFromAPI();

If the database takes 500ms and the weather API takes 800ms, your API is already waiting more than a second.
And that's before adding other work.
One simple improvement is doing independent operations in parallel:
const [user, weather] = await Promise.all([
getUserFromDatabase(),
getWeatherFromAPI()
]);

Instead of:
Database → 500ms
↓
Weather → 800ms

Total ≈ 1300ms

You can potentially get closer to:
Database ─── 500ms ──┐
├──→ Response
Weather ───── 800ms ─┘

Total ≈ 800ms

The exact result depends on the services and other work involved.
The important lesson:
Don't optimize only your code.
When an API is slow, ask:
"Where is the time actually being spent?"
Sometimes the slowest part of your API isn't your code at all.

Top comments (0)