API Performance: 15 Techniques That Hold Up Under Load
In this article
Slow APIs frustrate users, burn server resources, and cost you money. This guide walks through 15 practical techniques to improve API performance, from caching and database tuning to connection pooling and load testing. You'll learn what to implement first, how to measure the impact, and what to do when things don't go as planned. These techniques work for REST, GraphQL, and most backend frameworks.
What You'll Need
- Access to your API's codebase and deployment environment
- A load testing tool (e.g., k6, JMeter, Locust, or Artillery)
- Monitoring/observability setup (logs, metrics, tracing)
- Basic understanding of HTTP, caching, and database queries
Step-by-Step
- Measure your current baseline. Run a load test with realistic traffic patterns (e.g., 100 concurrent users, 10 requests/second) and record response times, error rates, and CPU/memory usage. You need a baseline to compare against after each change.
- Add response caching. Cache responses for GET endpoints that return static or semi-static data. Use HTTP headers like
Cache-Control: max-age=60and ETags. For dynamic data, use a reverse proxy cache (e.g., Redis, Varnish) to store serialized responses for a few seconds. - Implement database query optimization. Identify slow queries using your database's query log or EXPLAIN. Add indexes on columns used in WHERE, JOIN, and ORDER BY clauses. Avoid SELECT * — only fetch columns you need.
- Use connection pooling. Reuse database connections instead of opening a new one per request. Set a pool size that matches your workload (e.g., 10-20 connections per instance). Most ORMs (Hibernate, Sequelize, Django ORM) support pooling out of the box.
- Enable compression. Compress response bodies with gzip or Brotli. This can reduce payload size by 60-80%, especially for JSON. Make sure your web server (Nginx, Apache) or framework middleware is configured.
- Paginate large responses. Never return more than a few hundred records at once. Use cursor-based pagination for large datasets. This reduces payload size and database load.
- Add rate limiting. Protect your API from abuse and overloading. Use a token bucket or sliding window algorithm. This isn't just for security — it prevents a single client from hogging resources.
- Offload heavy tasks to background jobs. If an endpoint does something slow (like sending emails or generating reports), return a 202 Accepted and process the task asynchronously using a queue (e.g., RabbitMQ, Sidekiq, Celery).
- Implement HTTP/2 or HTTP/3. These protocols allow multiplexing, reducing latency. Most modern load balancers and web servers support them. Enable them if you haven't.
- Use a content delivery network (CDN). Serve static assets and even cached API responses from edge locations. This reduces round-trip time for global users.
- Optimize JSON serialization. Use a fast serializer (e.g., Jackson for Java, orjson for Python, System.Text.Json for .NET). Avoid reflection-heavy serializers. Also, consider using Protocol Buffers or MessagePack for internal services.
- Add timeouts and circuit breakers. Set timeouts for all external calls (database, third-party APIs). Implement circuit breakers to fail fast when a dependency is down, preventing cascading failures.
- Scale horizontally. Run multiple instances of your API behind a load balancer. Use auto-scaling based on CPU or request count. This is the most effective way to handle sudden traffic spikes.
- Profile your code. Use an application performance monitoring (APM) tool (e.g., New Relic, Datadog) to find bottlenecks. Look for slow database queries, N+1 problems, and inefficient loops.
- Re-test and iterate. After each change, run the same load test and compare against your baseline. Keep a changelog of what you changed and the impact. You'll likely need to revisit steps 2-4 multiple times.
Common Mistakes
- Ignoring the database. Most APIs are database-bound. Optimizing code without fixing slow queries will have minimal impact.
- Over-caching. Caching too aggressively can serve stale data. Always set appropriate TTLs and invalidate on writes.
- Not using indexes. Forgetting to add indexes on foreign keys or frequently queried fields is a classic mistake.
- Blocking the event loop. In Node.js, doing CPU-heavy work in the main thread blocks all requests. Use worker threads or offload to a separate service.
- Testing with too few users. Load testing with 10 users won't reveal bottlenecks. Use realistic concurrency levels.
Tips
- Start with caching and query optimization — they give the biggest wins for the least effort.
- Use a staging environment that mirrors production to test changes safely.
- Monitor not just response time, but also error rate and throughput.
- Consider using a read replica for read-heavy workloads.
- Keep your dependencies up to date — newer versions often have performance improvements.
Troubleshooting
If performance doesn't improve after caching: Check that your cache hit rate is high. If it's low, your cache key may be too specific (e.g., including a timestamp). Also, ensure you're caching at the right layer (reverse proxy vs. application).
If database queries are still slow after adding indexes: Run EXPLAIN to see if the index is being used. Sometimes the query optimizer chooses a full table scan because of a function on the column. Rewrite the query to avoid functions on indexed columns.
If your API becomes unstable under load: Check for memory leaks. Use a profiler to see if memory usage grows continuously. Also, look at garbage collection logs — frequent GC pauses can cause latency spikes.
If you're getting timeouts from external services: Increase timeouts gradually, but also implement retries with exponential backoff. Make sure you're not retrying too aggressively, which can overload the external service.
If horizontal scaling doesn't help: You might be hitting a bottleneck elsewhere — like the database or a shared cache. Scale those resources as well. Also, check if your load balancer is configured correctly (e.g., session affinity may be needed).
Frequently Asked Questions
What is the most important technique for API performance?
Caching is usually the most impactful, especially for read-heavy APIs. It reduces database load and response time significantly.
How do I know if my API is slow?
Measure the 95th percentile response time. If it's above 500ms for typical endpoints, users will notice. Also, monitor error rates and throughput.
Should I use REST or GraphQL for better performance?
GraphQL can reduce over-fetching, but it can also be slower if not optimized. REST is simpler to cache. The choice depends on your use case.
How often should I run load tests?
Run load tests after every major change, and regularly (e.g., monthly) to catch regressions.
What is the best load testing tool?
k6 is popular because it's scriptable and has good reporting. JMeter is also solid. Choose one that fits your team's skills.
Can I improve performance by using a faster programming language?
Sometimes, but the bottleneck is usually I/O (database, network) rather than CPU. Optimize your architecture first.