Your servers are struggling. Response times are climbing. Database connections are running out. Users are complaining. And your monitoring dashboard is turning into a Christmas tree.
Imagine you're responsible for an API that suddenly starts receiving 15,000 requests per second.
At first, everything looks fine. Requests are coming in, responses are going out, and the application is doing what it was designed to do.
Then things start getting interesting.
Some requests take 2 seconds instead of 100 milliseconds. Others return 503 Service Unavailable. Database connections are exhausted. CPU usage is approaching 100%, and your support team is receiving complaints faster than you can read them.
Your first instinct might be to add more servers.
But hold on.
What if the application isn't struggling because it needs more servers? What if it's struggling because every request is doing unnecessary work? What if your database is the real problem? Or perhaps your application is making thousands of identical requests to an external service.
Adding servers without understanding the bottleneck might simply give you more expensive servers that fail together.
So, let's approach this like engineers.
We have 15 minutes to stabilize the situation, and then we need to make sure it doesn't happen again.
Let's get to work.
1. First, understand what we're dealing with
Before touching the code, let's put the numbers into perspective.
15,000 requests per second means:
| Measurement | Traffic |
|---|---|
| Per second | 15,000 requests |
| Per minute | 900,000 requests |
| Per hour | 54 million requests |
| Per day (if sustained) | 1.296 billion requests |
That's a lot of work.
But here's something important: 15,000 requests per second doesn't automatically mean your application needs 15,000 servers or even a particularly large cluster.
The actual resource requirements depend on what each request does.
Consider two endpoints:
GET /products/123 And:
POST /orders/checkout The first might retrieve a product from Redis and return a small JSON response.
The second might:
- Authenticate the user.
- Validate the shopping cart.
- Check inventory.
- Calculate taxes.
- Process a payment.
- Update the database.
- Send notifications.
These requests have completely different costs.
This is why I wouldn't start by asking how many servers we need.
I'd start by asking:
What exactly is happening inside the application when a request arrives?
2. The first 15 minutes: Stop the bleeding
When a production system is failing, this isn't the time to rewrite your architecture or introduce five new technologies.
Our first objective is to restore service.
I'd divide the response into three priorities:
- Protect the system from further damage.
- Identify the biggest bottleneck.
- Restore acceptable performance without introducing new failures.
Minute 0–3: Understand the incident
I'd immediately look at our monitoring dashboards.
These are the metrics I'd care about most:
| Metric | What I'm looking for |
|---|---|
| Request rate | Is traffic unusually high? |
| Error rate | Are requests failing? |
| p95 latency | Are most users experiencing slow responses? |
| p99 latency | Are the slowest requests getting worse? |
| CPU utilization | Is the application CPU-bound? |
| Memory usage | Are we approaching memory exhaustion? |
| Database connections | Are connections exhausted? |
| Database query latency | Are queries taking too long? |
| Queue depth | Are background jobs falling behind? |
Why p95 and p99 instead of just average response time?
Because averages can be misleading.
Imagine 99 users receive responses in 100 milliseconds, but one user waits 10 seconds.
The average might still look reasonably healthy, but that last user has a terrible experience.
p95 tells us that 95% of requests complete within a particular time. p99 tells us the same for 99% of requests.
I want to understand the experience of users at the slow end, not just the average.
I'd also compare current metrics against the last known healthy baseline.
Minute 3–5: Protect the application
If traffic is overwhelming the system, we need to control how much work it accepts.
This is where rate limiting becomes useful.
For example, suppose one client is sending thousands of requests every second to an endpoint that should only be accessed occasionally.
We shouldn't allow that client to consume resources needed by everyone else.
A rate limiter can enforce a policy such as:
- 100 requests per minute per authenticated user.
- Lower limits for expensive endpoints.
- Higher limits for trusted internal services.
- Special limits for anonymous traffic.
The numbers are examples, not universal recommendations. Actual limits should reflect the endpoint's cost and legitimate usage.
We can also temporarily disable non-essential features, reduce expensive background operations, and use a circuit breaker when a failing external dependency is making the situation worse.
The goal is simple:
It's better to reject some unnecessary work than to allow the entire application to collapse.
Minute 5–10: Find the bottleneck
Now we investigate.
Suppose our monitoring reveals:
- CPU usage: 95%.
- Database CPU: 98%.
- Database connections: exhausted.
- p95 latency: 3 seconds.
- Error rate: increasing.
This tells us something important.
The application might not be the primary problem. The database is showing signs of serious pressure.
I'd inspect slow query logs, database metrics, connection-pool usage and query execution plans.
I'd also check distributed traces to see where requests spend their time.
For example:
Incoming HTTP request 2,850 ms | |-- Authentication 15 ms | |-- Business logic 35 ms | |-- Database query 2,700 ms | |-- JSON serialization 20 ms | |-- Response 80 ms This is a simplified example, but it tells us exactly where to investigate.
If 2,700 milliseconds are spent waiting for a database query, optimizing JSON serialization isn't going to save us.
Don't optimize the part of the application that looks interesting. Optimize the part that is actually causing the problem.
3. The database: Where performance problems love to hide
Let's say we've discovered that our product endpoint executes this query:
SELECT * FROM products WHERE category_id = 12 ORDER BY created_at DESC LIMIT 20; The application executes it thousands of times per second.
If the table contains millions of records and the database cannot efficiently locate and order the matching rows, the query can become expensive.
One possible improvement is an appropriate composite index:
CREATE INDEX idx_products_category_created ON products (category_id, created_at DESC); Now the database has a structure that can help it locate products belonging to a category and retrieve them in the required order.
However, indexes aren't free.
They consume storage and add overhead to inserts, updates and deletes.
I'd verify the improvement using:
EXPLAIN ANALYZE SELECT * FROM products WHERE category_id = 12 ORDER BY created_at DESC LIMIT 20; I want to see whether the database is using an efficient execution plan and whether the actual execution time has improved.
Another issue is unnecessary data retrieval.
Instead of:
SELECT * FROM products; We should retrieve only what the endpoint needs:
SELECT id, name, price, image_url FROM products; Why retrieve 40 columns when the client needs only four?
Less data means less database work, less network traffic and less serialization overhead.
Connection pooling matters too
Opening a new database connection for every request is expensive.
Imagine 15,000 requests arriving every second, each attempting to establish its own database connection.
That's a recipe for trouble.
Instead, we use connection pooling.
A pool maintains a controlled number of reusable database connections. Requests borrow an available connection, perform their database operation, and return it to the pool.
But there's a catch.
Increasing the pool size indefinitely isn't a solution either.
If ten application instances each maintain 500 database connections, that's potentially 5,000 connections competing for database resources.
We need to size pools based on the database's actual capacity and the application's workload.
The database must be protected, not overwhelmed by the application trying to help it.
4. Introduce caching: Stop doing the same work repeatedly
Now let's look at another opportunity.
Imagine thousands of users are requesting the same product information.
Does it make sense to query PostgreSQL every single time?
Probably not.
If the information doesn't change frequently, we can cache it.
This is where Redis becomes useful.
The basic idea:
- A request arrives.
- We check Redis for the requested product.
- If it exists, return it immediately.
- If it doesn't, retrieve it from PostgreSQL.
- Store the result in Redis.
- Return the response.
This is called the cache-aside pattern.
Here's a simplified Node.js example using Redis:
async function getProduct(productId: string) { const cacheKey = `product:${productId}`; // 1. Check Redis first const cachedProduct = await redis.get(cacheKey); if (cachedProduct) { return JSON.parse(cachedProduct); } // 2. Cache miss: query PostgreSQL const product = await db.product.findUnique({ where: { id: productId }, select: { id: true, name: true, price: true, }, }); if (!product) { return null; } // 3. Save the result for future requests await redis.set( cacheKey, JSON.stringify(product), "EX", 300 ); return product; } Now subsequent requests for that product can be served from Redis for up to five minutes.
The database doesn't have to repeat the same work every time.
But caching introduces new problems.
What happens when a product's price changes?
What if Redis becomes unavailable?
What if thousands of requests simultaneously miss the cache and all query the database?
These are real engineering problems.
We need to think about:
- Cache invalidation when underlying data changes.
- TTL (time to live) to prevent stale data from living indefinitely.
- Cache stampedes, where many simultaneous misses trigger expensive database queries.
- Fallback behavior when Redis is unavailable.
- Monitoring cache hit and miss rates.
Also, not everything should be cached.
A product description is a reasonable candidate.
A payment authorization result or an account balance requires much more careful consistency and security considerations.
Caching is not simply about making things faster. It's about making deliberate decisions about which data can safely be reused.
5. Scale horizontally, but do it intelligently
Let's assume we've optimized our queries and introduced caching.
Our application is still struggling.
Perhaps the application servers themselves are running out of CPU or memory.
Now horizontal scaling becomes a reasonable option.
Instead of depending on one large application server, we run multiple instances.
INTERNET | v LOAD BALANCER | +----------+----------+ | | | v v v API 1 API 2 API 3 | | | +----------+----------+ | SHARED SERVICES | +----------+----------+ | | v v REDIS POSTGRESQL A load balancer distributes incoming traffic across healthy application instances.
If we have three equally capable instances and distribute 15,000 requests per second evenly, each receives approximately:
15,000 / 3 = 5,000 requests per second That's the theoretical distribution, not a guarantee of capacity.
Actual performance depends on request complexity, instance resources, connection limits, network overhead and the load-balancing strategy.
There is another important consideration: stateless application design.
If API instance 1 stores a user's session only in its local memory, what happens when the load balancer sends the next request to API instance 2?
The second instance might not know who the user is.
We need shared session storage, signed tokens where appropriate, or another deliberate session-management strategy.
Application instances should ideally be replaceable without losing important user state.
This also makes deployments and recovery much easier.
6. Not every operation needs to happen immediately
Here's another common mistake.
We sometimes make users wait for work that doesn't need to happen before returning a response.
Imagine a user placing an order.
The application:
- Validates the order.
- Saves the order.
- Sends a confirmation email.
- Generates an invoice.
- Updates analytics.
- Notifies a warehouse.
Does the user need to wait for all six operations to finish before receiving confirmation?
Not necessarily.
Some of this work can happen asynchronously.
We can introduce a message queue.
USER | v ORDER API | v POSTGRESQL | v MESSAGE QUEUE | +--------+--------+ | | | v v v EMAIL INVOICE ANALYTICS WORKER WORKER WORKER The API handles the critical transaction and publishes an event for background processing.
Workers consume the messages independently.
Technologies such as RabbitMQ, Kafka, or cloud-managed queues can help implement this architecture, depending on the requirements.
But we need to be careful.
What if a message is delivered twice?
What if a worker crashes halfway through processing?
What if the database transaction succeeds but publishing the event fails?
These questions matter.
For reliable event publishing, the transactional outbox pattern is worth considering. It allows the application to save business data and an event record in the same database transaction. A separate process then publishes the event to the message broker.
We also need idempotent consumers, retries with backoff, dead-letter queues and monitoring of queue depth.
Moving work to a queue doesn't eliminate complexity. It changes where we manage that complexity.
And that's an important engineering trade-off.
7. Protect the system from dependencies
Our API doesn't operate in isolation.
It might depend on:
- A payment provider.
- An email service.
- An authentication provider.
- A third-party shipping API.
- Another internal service.
Now imagine our payment provider starts responding slowly.
If every API request waits indefinitely for that provider, our application can run out of available resources.
This is where timeouts, retries and circuit breakers become important.
A timeout prevents a request from waiting forever.
A retry can recover from temporary failures, but retries must be controlled. Retrying aggressively can make an already struggling service even worse.
A circuit breaker helps prevent repeated calls to an unhealthy dependency.
Its basic states are:
Closed: Requests are allowed through normally.
Open: Requests are blocked temporarily because failures have exceeded a threshold.
Half-open: A limited number of requests are allowed through to check whether the dependency has recovered.
The objective is to prevent one failing service from taking down everything connected to it.
A resilient system doesn't assume that every dependency will always be available.
It plans for failure.
8. How do we prove our changes actually worked?
This is where I think engineering becomes particularly interesting.
We can make ten architectural changes, introduce three caching layers and deploy more servers.
But how do we know whether we've actually improved anything?
We measure.
I'd use a load-testing tool such as k6 to simulate realistic traffic.
For example:
import http from "k6/http"; import { check, sleep } from "k6"; export const options = { scenarios: { api_load: { executor: "ramping-arrival-rate", startRate: 1000, timeUnit: "1s", preAllocatedVUs: 100, maxVUs: 5000, stages: [ { target: 5000, duration: "2m" }, { target: 10000, duration: "2m" }, { target: 15000, duration: "3m" }, ], }, }, thresholds: { http_req_failed: ["rate<0.01"], http_req_duration: ["p(95)<300"], }, }; export default function () { const response = http.get( "https://api.example.com/products/123" ); check(response, { "status is 200": (r) => r.status === 200, }); sleep(1); } This is an illustrative starting point, not a production-ready test configuration.
The arrival-rate executor attempts to generate the specified number of iterations per second. We should account for the number of HTTP requests each iteration makes, and monitor whether the load generator itself becomes the bottleneck.
The thresholds give us measurable targets:
- Fewer than 1% failed requests.
- p95 response time below 300 milliseconds.
These are example service objectives, not universal standards.
I'd also test:
- Normal traffic.
- Sudden traffic spikes.
- Sustained high traffic.
- Traffic that gradually increases.
- Failure of Redis.
- Database connection exhaustion.
- Slow external dependencies.
And I wouldn't only test whether the application survives.
I'd also test whether it recovers gracefully.
A system that handles a traffic spike but takes 30 minutes to recover might still be a poor production system.
9. What would our final architecture look like?
After addressing the immediate problems, our architecture might evolve into something like this:
INTERNET | v CDN / EDGE LAYER | v LOAD BALANCER | v API GATEWAY / WAF | +--------------+--------------+ | | | v v v API 1 API 2 API 3 | | | +--------------+--------------+ | +----------+----------+ | | v v REDIS POSTGRESQL | | | CONNECTION POOL | | +----------+----------+ | v MESSAGE BROKER | +------------+------------+ | | | v v v EMAIL REPORTS ANALYTICS WORKER WORKER WORKER Each component has a responsibility.
- CDN: Caches suitable static and public content closer to users.
- Load balancer: Distributes traffic across healthy instances.
- API gateway/WAF: Applies routing, security and traffic policies.
- API instances: Handle business logic.
- Redis: Handles suitable frequently accessed data.
- PostgreSQL: Maintains durable relational data.
- Connection pooling: Controls database connection usage.
- Message broker: Decouples background operations.
- Workers: Process asynchronous jobs.
I'd also add observability across the system using metrics, structured logs and distributed tracing.
For deployment, I'd consider containerization, automated health checks, rolling deployments and autoscaling based on meaningful signals.
But notice something:
We haven't introduced every possible technology just because it exists.
Every component should solve a demonstrated problem.
If our application doesn't need Kafka, we shouldn't introduce Kafka simply because we're expecting a lot of traffic.
If a modular monolith can handle our requirements, we don't need 15 microservices.
Good architecture isn't about having the most components. It's about having the right components.
10. The lessons I'd take away
If I had to respond to this incident, these are the principles I'd keep in mind:
- Measure before optimizing. Guessing is expensive, especially during production incidents.
- Protect the database. A healthy application can still fail because its database cannot keep up.
- Cache intelligently. Avoid repeating expensive work when the data can safely be reused.
- Scale based on evidence. More servers don't automatically mean more capacity.
- Move non-critical work off the request path. Users shouldn't wait for tasks that can happen asynchronously.
- Expect dependencies to fail. Timeouts, circuit breakers and controlled retries are essential.
- Test realistic traffic. A successful test with 100 requests per second tells us very little about behavior at 15,000.
- Design for recovery. Surviving an incident is important, but recovering from one matters just as much.
And perhaps the most important lesson:
Performance is not a feature you add at the end. It's a property you build into the system through deliberate engineering decisions.
Final thoughts: The real challenge isn't handling 15,000 requests.
It's handling them without compromising the experience of the people using your software.
A system can process millions of requests and still be poorly engineered if users experience slow responses, lost transactions, inconsistent data or unexpected failures.
The goal isn't simply to make an API fast.
It's to make it dependable.
When I think about software engineering, I find that the most interesting problems are rarely solved by adding more code. They're solved by understanding what's happening, questioning our assumptions, identifying the real constraints and making informed trade-offs.
That's the kind of engineering I want to keep learning and practicing.
And I'd love to hear how other engineers would approach this scenario.
