Performance

API Performance Optimization: Strategies for Speed and Efficiency

How to make an API faster: measure latency percentiles, cut database round trips, cache at the right layer, compress responses and scale out.

By the APIStack team··Updated ·11 min read

A laptop on a desk showing an analytics dashboard with charts

This article covers the changes that most often make a slow API faster: measuring properly, doing less database work per request, caching, compressing responses and running more than one instance. It is written for developers who run an HTTP API backed by a database. The examples use Node.js with Express, PostgreSQL and Redis, but the reasoning applies to any stack.

The order matters. Measurement comes first because the slow part of a request is rarely where you expect, and each later step is only worth doing if the numbers say so.

Measure before you change anything

Four numbers describe how an API is performing. Latency is how long a request takes from the server's point of view. Throughput is how many requests are completed per second. Error rate is the share of requests that fail. Saturation is how close a resource such as CPU, memory or the database connection pool is to its limit.

Record latency as a distribution, not an average. An average hides the slow requests that users notice, so track percentiles: the median (p50) shows the typical case, and p95 or p99 show the slow tail. A histogram metric gives you percentiles per route without storing every request.

The middleware below records a duration histogram with prom-client, the Prometheus client for Node.js, and exposes it on /metrics for a Prometheus server to scrape.

JavaScript
const client = require('prom-client');

const httpDuration = new client.Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests in seconds',
  labelNames: ['method', 'route', 'status_code'],
  buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5]
});

app.use((req, res, next) => {
  const end = httpDuration.startTimer();
  res.on('finish', () => {
    end({
      method: req.method,
      route: req.route ? req.baseUrl + req.route.path : 'unmatched',
      status_code: res.statusCode
    });
  });
  next();
});

app.get('/metrics', async (req, res) => {
  res.set('Content-Type', client.register.contentType);
  res.end(await client.register.metrics());
});

The route label uses the route pattern (/users/:id), not the request path (/users/123). Labelling by raw path creates a new time series for every distinct URL, which eventually exhausts memory in both the process and the metrics server. A histogram also counts observations, so you get request and error counts from the same metric without a separate counter.

With this in place, find the routes with the worst p95 and the highest traffic, and work on those. For what to do with the metrics once you have them, see Monitoring and Analytics for API Performance.

Reduce database work

For most APIs the database accounts for the largest part of the response time. Three problems cause the majority of it: opening connections per request, running many small queries where one would do, and reading more rows than the response needs.

Pool connections

Opening a database connection involves a TCP handshake, usually a TLS handshake, and authentication. Doing that on every request adds latency and puts connection churn on the database. A pool keeps a fixed number of connections open and lends them to requests.

With the pg library, create one pool for the process and call pool.query on it. The pool checks a connection out, runs the query and returns the connection, even if the query throws.

JavaScript
const { Pool } = require('pg');

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20,                       // connections this process may hold
  idleTimeoutMillis: 30000,      // close connections idle for 30 s
  connectionTimeoutMillis: 2000  // fail fast when the pool is exhausted
});

async function getUserById(id) {
  const { rows } = await pool.query(
    'SELECT id, name, email FROM users WHERE id = $1',
    [id]
  );
  return rows[0];
}

Check out a client manually with pool.connect() only when several statements must share a connection, as in a transaction, and release it in a finally block.

Size the pool against the database's limit, not the application's appetite. The total across all instances (max multiplied by the number of processes) has to stay below the server's connection limit. On serverless platforms, where each function instance holds its own pool, put an external pooler such as PgBouncer in front of the database.

Remove N+1 queries

An N+1 query pattern loads a list with one query and then runs one more query per item. Fifty users means fifty-one round trips, and each round trip costs network time even when the query itself is fast.

JavaScript
// One query for the users, then one per user
const { rows: users } = await pool.query('SELECT id, name FROM users LIMIT 50');
for (const user of users) {
  const { rows } = await pool.query(
    'SELECT id, title FROM posts WHERE user_id = $1',
    [user.id]
  );
  user.posts = rows;
}

The fix is to fetch all the children in a single query and group them in memory. This version always makes two round trips, whatever the number of users.

JavaScript
async function getUsersWithPosts() {
  const { rows: users } = await pool.query(
    'SELECT id, name FROM users ORDER BY id LIMIT 50'
  );
  const { rows: posts } = await pool.query(
    'SELECT id, user_id, title FROM posts WHERE user_id = ANY($1)',
    [users.map((user) => user.id)]
  );

  const byId = new Map(users.map((user) => [user.id, { ...user, posts: [] }]));
  for (const post of posts) byId.get(post.user_id).posts.push(post);
  return [...byId.values()];
}

A JOIN also works, but it repeats the parent columns on every child row and you still have to group the rows afterwards. ORMs cause N+1 queries silently through lazy loading, so log the number of queries per request in development and investigate any route where it grows with the result size.

Index and paginate

Select only the columns the response uses, and make sure the columns in WHERE, JOIN and ORDER BY clauses are indexed. Run EXPLAIN ANALYZE on slow queries to confirm that the planner uses the index. Indexes are not free: each one slows writes and takes storage, so add them for queries you actually run.

Never return an unbounded collection. OFFSET pagination is simple but the database still reads and discards every skipped row, so deep pages get slower. Keyset pagination filters on the last value the client saw and stays fast at any depth.

SQL
SELECT id, title, created_at
FROM posts
WHERE user_id = $1
  AND id < $2          -- id of the last post on the previous page
ORDER BY id DESC
LIMIT 20;

Cache at the right layer

Caching trades freshness for speed, so it suits data that is read far more often than it changes and where a slightly stale answer is acceptable. There are two places to cache: in front of the API using HTTP, and inside it using a store such as Redis.

HTTP caching

If a response is the same for every caller, let clients and CDNs keep it. The Cache-Control header says who may store a response and for how long, as defined in RFC 9111.

JavaScript
app.get('/api/countries', async (req, res, next) => {
  try {
    res.set('Cache-Control', 'public, max-age=3600');
    res.json(await getCountries());
  } catch (err) {
    next(err);
  }
});

Use private instead of public for responses that depend on who is asking, and no-store for anything sensitive. Express also adds an ETag to JSON responses by default and answers a matching If-None-Match request with 304 Not Modified. That saves the transfer but not the work of building the response.

Application caching with Redis

For data that is expensive to compute, use the cache-aside pattern: look in the cache, fall back to the source on a miss, then store the result with a time to live (TTL). The helper below uses the redis package, version 4 or later. A cache failure must never fail the request, so both cache operations catch their own errors, and the source is queried exactly once.

JavaScript
const { createClient } = require('redis');

const redis = createClient({ url: process.env.REDIS_URL });
redis.on('error', (err) => console.error('Redis error:', err.message));
redis.connect().catch(() => {});

async function cached(key, ttlSeconds, fetchFn) {
  try {
    const hit = await redis.get(key);
    if (hit !== null) return JSON.parse(hit);
  } catch (err) {
    console.error('Cache read failed:', err.message);
  }

  const data = await fetchFn();
  redis.set(key, JSON.stringify(data), { EX: ttlSeconds })
    .catch((err) => console.error('Cache write failed:', err.message));
  return data;
}

app.get('/api/products/:category', async (req, res, next) => {
  try {
    const { category } = req.params;
    const products = await cached(`products:${category}`, 1800, () =>
      db.getProductsByCategory(category)
    );
    res.json(products);
  } catch (err) {
    next(err);
  }
});

Choose the TTL from how stale the data is allowed to be, and delete the key when the underlying data changes if the TTL alone is too slow. Include everything that changes the result in the key: the category here, and the user or tenant ID for per-user data. Leaving the user out of the key is how one customer ends up seeing another customer's data.

The same pattern applies to third-party APIs your service depends on. Holiday calendars, exchange rates and geocoding results change slowly, so caching them removes a network call from your request path and keeps you inside the provider's quota. With the Public Holidays API, for example, a year of holidays per country can be cached for days. That matters on the APIStack free plan, which allows 1,000 calls a month at 10 a minute (see rate limits and quotas).

Compress responses

JSON is repetitive text and compresses well. Compression costs CPU time on the server and saves transfer time on the network, which is a good trade for large responses on slow connections and a poor one for tiny payloads.

In Express, the compression middleware negotiates an encoding with the client through the Accept-Encoding header and compresses matching responses.

JavaScript
const compression = require('compression');

app.use(compression({
  threshold: 1024 // skip responses smaller than 1 KB
}));

The middleware already skips content types that are not compressible, such as images. If a reverse proxy or CDN sits in front of the application, compress there instead and leave the middleware out, so the work is done once and off the application's CPU.

Compression reduces bytes on the wire but the server still has to build the full response. A smaller payload is better than a compressed large one, so paginate collections and let clients ask for only the fields they need.

Scale out

When one instance is saturated and the code is already efficient, run more instances behind a load balancer. This only works if the instances are stateless: sessions, caches, rate-limit counters and uploaded files have to live in a shared store such as Redis, the database or object storage, not in process memory or on local disk.

The Docker Compose file below runs four replicas of an API and an nginx container in front of them. The replicas do not publish ports of their own; only nginx is reachable from outside.

YAML
services:
  api:
    image: my-api:latest
    environment:
      - NODE_ENV=production
      - DATABASE_URL=${DATABASE_URL}
    deploy:
      replicas: 4

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      - api

Every replica listens on port 3000 and is reachable under the service name api. nginx resolves that name to all the replica addresses when it starts and distributes requests among them.

Text
upstream api {
    least_conn;
    server api:3000;
}

server {
    listen 80;

    location /api/ {
        proxy_pass http://api;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Because nginx resolves the name only at startup, reload it after changing the number of replicas. An orchestrator such as Kubernetes, or a managed load balancer, handles that discovery and health checking for you.

More instances multiply database connections, so revisit the pool size when you scale. If the database is the bottleneck, adding API instances makes things worse; read replicas, caching or query fixes are the right tools in that case.

Summary

  • Measure first. Record latency as a histogram per route, look at p95 and p99, and work on the routes that are both slow and busy.
  • Most latency comes from the database: pool connections, replace N+1 loops with a single batched query, index the columns you filter on, and paginate every collection.
  • Cache responses that are read often and change rarely, with HTTP headers for shared data and Redis for expensive lookups. Put everything that affects the result in the cache key.
  • Compress large text responses in one place, either the application or the proxy, and prefer sending less data in the first place.
  • Scale horizontally only once instances are stateless, and check that the database can take the extra connections.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading