Our system has been slowing down for two years: should we add servers or change the code first?
Don't choose between "add servers" and "change code" yet — they don't cure the same disease. Adding servers fixes a shortage of resources: CPU, memory, or connection counts maxed out, so requests can only queue. Changing code fixes doing too much in a single request: scanning hundreds of thousands of rows to fetch ten records, or recomputing a full-year total every time a page opens. When a system slows down after a year or two, most of the time it is the latter, because the data keeps growing and the cost of queries, aggregates, and pagination grows with it. Adding machines then usually just pushes the problem out a few months, while the bill is permanent.
A more reliable first step is not to pick a plan but to spend a few days turning "slow" into something you can point at: which role, on which page, at what data volume, how many seconds, and whether it is always slow or intermittent. With that baseline, "add servers or change code" stops being a matter of opinion and becomes arithmetic backed by evidence: what does fixing this one place cost, how long will it hold, and how does that compare with the annual cost of another machine.
Why "suddenly slow" has actually been building for a long time
Users almost never experience slowness as something that happened on one particular day. It arrives in steps: nothing noticeable in the first year, the occasional spinner in the second, and by the third "don't open that report at month-end". The reason is that the trigger conditions are gradual; at no point does anything raise an error, and every monitoring chart stays green.
The common causes fall into three groups, each diagnosed differently:
The data is growing. The same query, the same code, the same server: last year it scanned 20,000 rows, this year it scans 800,000, and the time grows with it. The signature is that the feature has not changed, the interaction has not changed, the same operation simply takes longer. It shows up most often in lists, search, exports, and statistics, because those four naturally "touch a lot of data".
Usage patterns have changed. In the early days only a few people used the system; later stores, dealers, and external integrations were added, and both concurrency and usage hours changed. A system with ten simultaneous users and one with three hundred rarely expose the same problems: connection pools running out, lock waits, third-party rate limits — all of these appear only after concurrency rises. The signature is "slow when many people are on, fine when few are", concentrated in particular time windows.
External dependencies are degrading. A payment gateway, SMS, maps, object storage, some upstream system — any one of them slowing down makes the whole thing slow, while your own server metrics may stay healthy the entire time. This is the easiest kind to misdiagnose, because the team is staring at its own machines and sees nothing wrong.
When the three are mixed together, the discussion turns into mutual blame: the business says the system is bad, engineering says the servers are weak, operations says the code is badly written. The only thing that ends that discussion is one fact: which layer is consuming the time.
Layer the problem with three pieces of evidence
You don't need an architecture review to start. Three pieces of evidence usually sort 80% of problems into a few categories, and all three can be obtained within a week.
First: look at when the slowness happens and which operations it covers. Is every page slow, or only a few features? Is it even across the day, or concentrated around the morning meeting, month-end, or promotions? If only one page is slow, the problem is basically in that piece of code and the tables it queries; only when everything is slow do resources and global configuration come into play. If it clusters in particular hours, suspect concurrency first, and batch jobs colliding with each other.
Second: run a comparison against a small data set. Point the same code at a backup from a year ago and run the same operations. If it is clearly faster, the time is mainly determined by data volume, which points to the first and third bottleneck types; if it is just as slow, row counts are not the issue and you should look at external calls, the network, and missing caches. This comparison is worth a lot because it changes nothing and still eliminates half the hypotheses outright.
Third: look at resource levels and waiting. CPU, memory, disk IO, database connections, slow query logs — what you want to know is "is anything maxed out" and "what are we waiting on". The most common misread here: CPU at 20% but everything is slow, so the conclusion is "the machine is fine", when in fact the bottleneck is waiting on locks, on random disk reads, or on an external API that times out and retries. Conversely, CPU persistently above 80% with connections often at the ceiling means adding resources really is the right medicine.
With all three in hand you usually reach a very specific conclusion, for example: "once the order list passes two million rows, paging backwards by date takes over ten seconds; database CPU is low but disk reads are high." At that point the plan basically surfaces on its own.
Four common bottlenecks, with very different remedies and costs
1. The query itself scans the whole table
Typical signs: list pages get slower the further you page, filtering by date or status is slow, exports are slow, while a single detail page is fast. The cause is usually that indexes no longer match the real query conditions: the UI supports "by status + by date + by keyword" combined filtering, but the database has only a primary key index; or a leading-wildcard fuzzy match makes the index unusable; or large-offset pagination means that at page two thousand the database still has to count out the first few hundred thousand rows and throw them away.
This is the highest-value repair target. The approach is to build composite indexes that match the real query conditions, align the order of filter and sort fields, and replace large-offset pagination with cursor-based pagination. The cost is small, usually measured in person-days; the risk is clear too: more indexes is not better, a wrong one slows writes and takes space, and indexing a large table needs an off-peak window with time reserved. Whether it worked is not a matter for debate: run the same query before and after and compare the execution plan and the elapsed time.
2. Every request computes on the spot
Signs: the home page, dashboards, and reports open slowly, and slow down "very consistently" — every time you wait about as long. The cause is usually real-time aggregation: opening a page counts the whole table, groups by a full year of data, or queries related tables one by one inside a loop (the so-called N+1 query). At small data volumes these patterns cost nothing; once volume rises they become a hard defect.
The remedy is to compute ahead: turn summaries into scheduled jobs that write to summary tables and let pages read the results; put hot data in a cache with proper invalidation rules; make exports and large calculations asynchronous, notifying the result when done. The cost is medium, because data flows have to change; the risk is concentrated in the same place — once the summary table and the detail table disagree on definitions, users see "the totals don't match", and that damages trust more than slowness does. So pre-aggregation must define the metrics at the same time, keep the ability to drill down from summary to detail, and include reconciliation in acceptance.
3. Data only grows; hot and cold are mixed together
This is the most typical disease of an "old system". After three years of business, orders, logs, transactions, and message records are all piled into the same set of tables, and a query for "the last three months" still searches an index that spans three years of data. The symptom is that it gets slower the longer it is used, and index tuning only relieves it.
The remedy is layering: partition by time, move historical data into a history database or cold storage, and keep only the window online business needs in the primary database. The technical difficulty here is not the highest; what is hard is the business decision — which data may leave the primary database, how long it is kept, who can still query it, and whether querying it requires approval. Financial vouchers, contracts, and audit logs often carry statutory or internal-control retention requirements and cannot be deleted in the name of "performance". So an archiving plan has to be agreed with the business and finance, and it must keep the reporting definitions unchanged: a monthly report should give the same numbers before and after archiving, otherwise you have created a new reconciliation problem.
4. Genuine capacity shortage
If all three pieces of evidence point to resources being maxed out, then the capacity really is insufficient. The remedies are bigger instances, read replicas to spread queries, splitting by business domain, and rate limiting at the front end. These work quickly, cost money continuously, and come with a premise that is easy to overlook: horizontal scaling requires the application itself to be stateless. If sessions live in local memory, files are written to the machine's local disk, and scheduled jobs run on every node, adding machines does not solve the problem — it creates new inconsistencies.
| Bottleneck type | Typical signals | First choice of remedy | Cost and risk | Does adding machines help |
|---|---|---|---|---|
| Full-table scans in queries | A single list or export is slow; detail pages are fine | Add indexes, change pagination, narrow query conditions | Low cost; large-table indexing needs an off-peak window | Mostly no; it only defers the slowness |
| Recomputing on every request | Dashboards and reports are consistently slow | Pre-aggregation, caching, async processing | Medium; high risk of metric drift | Partly; cost keeps rising with data volume |
| Hot and cold data mixed together | Older systems get slower; even recent queries are slow | Partitioning, archiving, hot/cold separation | Medium-high; involves retention and compliance judgment | Short-term relief; congestion returns |
| Genuine capacity shortage | CPU, memory, connection counts maxed | Bigger instances, read replicas, splitting, rate limiting | Ongoing cost; depends on a stateless application | Yes, but set scaling thresholds at the same time |
When adding machines doesn't help
This deserves its own section because it is the step companies take first and the one most likely to waste money.
When a single query has to scan the whole table, adding CPU only turns "scanning slowly" into "scanning slowly on many cores"; the elapsed time will not drop to something users accept. Under heavy lock contention, more machines mean more requests fighting over the same lock, and waits get longer. A single database and table has a write ceiling, and adding application servers does nothing for a write bottleneck. If an upstream API times out, no amount of local capacity lets you do anything but wait. Slowness on the user's side can also come from oversized front-end assets or uncompressed images, which has nothing to do with the server.
So a practical rule: if the slowness can be pinned to "a specific operation at a specific data volume", change the code first; if it shows up as "everything slows the moment concurrency rises, resource metrics max out at the same time, and the application is stateless", adding resources is the right answer. The two can be done together, but the order should not be reversed.
A cost-ordered sequence of remedies
The order below is not optimal for every project, but it puts "risk of change" and "cost of verification" ahead of money, which suits most systems that are already live and still doing business.
- Define "slow" first. Work with the business to list three to five operations that most affect revenue or efficiency, and write down the role, the entry point, the current data volume, and the longest acceptable wait. Without that list, none of the later optimization can be accepted.
- Collect evidence over a full cycle. Slow query logs, API latency, resource monitoring — cover at least one business peak (month-end close, a promotion, a scheduling crunch). Looking only at off-peak data will miss the real bottleneck.
- Attribute every slow operation. Tag it with one of the four types above and estimate the blast radius: how many people use it, how often, how much longer they wait. Do the high-impact ones first, even if they are not the most technically elegant.
- Start with low-cost, high-certainty changes. Indexes, pagination, hot-data caching, turning synchronous batch operations into asynchronous ones. This tier usually recovers most of the experience without major structural change.
- Then do structural work. Partitioning and archiving, read/write separation, moving reporting off the primary database. This tier needs scheduling, downtime windows, and business sign-off on retention.
- Add resources last, and set trigger thresholds at the same time. For example, when data volume or concurrency reaches a certain level, or a monitoring metric stays above a value for a certain period, the next round of scaling or optimization starts — rather than waiting for user complaints.
- Re-measure with the same metrics and keep a record. Baseline before, result after, and the data volume at each point. That way, the next time it slows down, the team can tell whether it has "grown again" or "regressed".
Three traps that cause the most rework
Acting without a baseline. Optimizing by feel, then hearing users say "seems a bit faster" with no way to prove it. Worse, when it slows again months later, nobody knows what was changed last time or how much data there was then.
Load testing only total throughput, not real operation mixes. The load test hammers "random detail page views" and the numbers look great, but real users open reports, export details, and approve batches at the same time at month-end. When the test scenario doesn't match reality, the conclusion is unusable.
Archiving quietly changes the reporting definitions. Moving two-year-old data away for performance changes the denominator of the annual report and finance can't reconcile. Before archiving you must freeze the definitions, reconcile before and after, and make sure historical queries have a clear entry point.
How to write acceptance criteria so handover doesn't turn into an argument
Performance problems turn into arguments easily because "fast" and "slow" are adjectives. What goes into acceptance should be measurable:
- Target operations and metrics: which operations, at what data volume and concurrency, reach what response time (P95 rather than the average, which hides the poor experience of that small group) and what error rate.
- Environment and data: test on production-equivalent data, or on a scaled-down set with the scaling rationale stated. Conclusions drawn from ten thousand test rows do not represent production.
- Observation window: several full business cycles including one peak, not a glance on launch day.
- What is not promised: not "never laggy", only the agreed metrics at the agreed data volume and concurrency, plus what happens beyond that.
- Triggers for the next optimization: at what data volume, concurrency, or duration the next evaluation starts — best written into the contract or the operations agreement.
This style also helps the client: it turns "your system is bad" into "at this data volume, this operation did not meet the agreed metric", and both sides can talk about the same record.
How Boiling Water handles this kind of problem
In custom projects we prefer to hold data-growth performance down during design and handover rather than wait for it to erupt:
- During design, index and query review, list pagination, report pre-aggregation, and logging and monitoring are part of the deliverable rather than an after-launch extra; when an app, a mini program, and an admin back end are involved, each one's data-loading approach is reviewed separately.
- At go-live handover we provide a capacity baseline: current data volume, growth rate of the main tables, and the current scaling trigger point, so the client's operations team knows what to prepare and when.
- For systems already live, we start with read-only diagnosis: read logs, monitoring, and execution plans without touching production data, and produce a bottleneck list ordered by impact and cost of change, with the client deciding which tier to do first. The diagnosis explicitly separates "optimizable at the code layer" from "needs capacity at the infrastructure layer", so budget doesn't go to the wrong place.
- Boundaries are stated clearly: query and code-level performance optimization fall under continuous iteration; capacity exhaustion, monitoring alerts, and backup/recovery fall under operations services; both are separate from fixing defects in the delivered software. See the scope of the software maintenance policy and system operation assurance.
What the client needs to provide is not much: the real current data volume and how it is growing, a few specific "slow" operations and when they happen, how long a downtime window is acceptable, and a rough budget range. The client does not need to decide whether to add machines or change code — that is exactly the question our diagnosis is meant to answer.
If the system is still at the selection or first-build stage, "what happens when data grows tenfold in two years" can go straight into the solution review; custom development conversations usually cover it at the scope stage.
Closing
"Getting slower" is not a question to settle with money; it is a question to locate with evidence first. Slowness caused by data growth comes mostly from how queries are written, when calculations happen, and how data is layered; those changes usually cost less than a year of machine bills, and they don't push the problem into next year. When resources really are needed, set the scaling triggers at the same time — otherwise the next "sudden slowdown" will again have the team guessing from zero.
A few common follow-up questions
Is adding memory the easiest option?
If the evidence shows a low cache hit rate and frequent buffer pool churn, more memory is genuinely good value. But if the slowness is in rows scanned and lock waits, filling memory won't help.
Can we just switch to a stronger database?
Switching databases is a migration project, not an upgrade. At mid-to-large data volumes the risk of migration itself (type differences, SQL dialects, regression testing, downtime) often outweighs the benefit. Usually you fix queries and layering first, then evaluate whether a switch is really needed.
The cloud provider says scaling up will solve it — should we believe that?
Scaling up addresses resources. It has no effect on how your system writes queries, and none on a slow upstream API. You can scale up, but ask for evidence of current resource utilization, and for what to investigate next if it is still slow afterwards.
Sources
The performance judgments and the sequence of remedies above are engineering practice advice, not a commitment about the latency of any specific system. Boiling Water's service scope and the boundary between maintenance and operations are quoted from public pages on this site (software maintenance policy, system operation assurance), which is the company's own disclosure. Data retention periods and archiving requirements for financial vouchers and audit logs must be confirmed separately under the client's industry and internal-control rules; this article does not replace legal or audit advice. No third-party measured data is cited and no specific performance figures are given; actual metrics should be measured in tiers under real data volumes and concurrency.