Capacity from measurements

You can turn measured throughput and latency into a capacity statement with explicit headroom before deciding what to scale or optimize.

Learning outcomes

  • Convert k6 throughput, p95, p99 and error-rate measurements into a sustainable capacity estimate.
  • Identify the first resource to reach saturation and calculate operating headroom.
  • Estimate application instances, MySQL query load, Redis capacity and order write throughput from measured traffic.
  • Apply Little's Law, peak factors and storage estimates while accounting for the differences between theoretical estimates and observed behaviour.
  • Write a reproducible capacity statement that documents hardware, workload, latency targets, resource limits and scaling assumptions.

Your k6 scripts now produce before numbers for restaurant browsing and order creation. The next problem is deciding what those numbers mean for deployment: how much traffic can the backend sustain while meeting its latency target, and which resource limits it first? You need to turn the measurements into a capacity statement rather than report the highest request rate the load generator achieved.

Measured capacity and theoretical estimates

The capacity lessons from Weeks 1 to 5 introduced theoretical estimates for rate limiter checks, order-service writes, Kafka processing and mobile client request rates.

Those estimates gave you an initial idea of the resources the backend might need. Now you can compare them with actual measurements.

Capacity estimation combines workload assumptions with measured resource usage. The goal is to estimate how much traffic the deployed system can handle while meeting its service targets.

The two k6 workloads measure different parts of the food-delivery backend:

WorkloadWhat it exercises
Restaurant browsingRestaurant listing, menu retrieval and Redis menu caching
Order placementCustomer authentication, MySQL transactions and outbox publishing

The browse workload defaults to 300 virtual users for three minutes. The order workload ramps to 100 orders per second and sustains that rate.

These are test configurations, not production capacity guarantees.

A useful capacity estimate answers several questions:

  • What request rate can the API sustain?
  • What p95 and p99 latency does it maintain at that rate?
  • What percentage of requests fail?
  • Which resource reaches its limit first?
  • How much headroom should remain during ordinary operation?
  • How many application instances and what database and Redis capacity does the expected traffic require?

The highest request rate is not automatically the best result.

Consider two hypothetical measurements:

Throughputp95 latencyError rate
2,000 RPS2,000 ms0.2%
1,800 RPS120 ms0.2%

The second configuration handles fewer requests per second, but its response latency is substantially lower.

The service target determines which result is acceptable. You should not maximize throughput without considering customer experience.

Sustainable request rate

The requests per second (RPS) measurement tells you how much HTTP work the service completes over time.

For capacity planning, distinguish the configured arrival rate from the achieved completion rate.

An open k6 workload can schedule 100 order iterations per second. However, the API might complete fewer requests because it is overloaded or the load generator cannot sustain the schedule.

Use completed HTTP requests and achieved throughput when evaluating the result.

Throughput and latency together

Start by examining three measurements:

  • Throughput: completed requests per second.
  • Latency: especially p95 and p99.
  • Error rate: the proportion of failed requests.

p95 represents the request duration below which approximately 95% of measured requests fall. p99 represents the corresponding boundary for approximately 99% of requests.

The average can hide slow requests. This is particularly relevant when database queries occasionally take much longer than normal.

Consider these illustrative browse results:

Throughputp95Error rate
500 RPS45 ms0.0%
1,000 RPS65 ms0.1%
1,400 RPS85 ms0.1%
1,800 RPS120 ms0.2%
2,000 RPS240 ms0.8%
2,200 RPS510 ms3.5%

Assume your service target is:

p95 latency: below 150 ms
Error rate:  below 1%

The highest measured rate meeting both requirements is 1,800 RPS.

At 2,000 RPS, the error rate remains within the target, but p95 latency exceeds the latency requirement. At 2,200 RPS, both latency and error rate violate their targets.

The sustainable rate is therefore 1,800 RPS under these measured conditions.

The latency curve

The sharp increase in latency as traffic rises is called the knee of the curve.

At lower request rates, the service handles additional work without a large increase in response time. Near saturation, additional traffic causes disproportionately higher latency.

This is a useful signal that a resource is approaching its limit.

Do not assume that the exact rate at the knee is always the maximum sustainable capacity. The service target determines the acceptable operating point.

Repeated measurements

A single successful run does not establish a reliable capacity limit.

Repeat the same workload under equivalent conditions. Hold each traffic stage long enough to observe stable behaviour.

Use load stages to increase traffic gradually. Record completed RPS, p95, p99 and error rate at each stage.

A k6 threshold can stop a workload when a performance requirement is violated. This prevents you from spending unnecessary time testing a configuration that has already exceeded an important limit.

Keep the before numbers and after numbers from the same script and workload. Otherwise, you cannot confidently attribute a performance difference to the implementation change.

Resource saturation

A service reaches Saturation when a resource becomes sufficiently constrained that additional work causes queues to form and latency to increase.

The resource might be CPU, MySQL connections, Redis, network capacity or even the load generator.

A resource does not need to reach 100% utilization before it becomes the bottleneck. For example, a connection pool with a small maximum can start producing waits while the database server itself still has available CPU.

Watch the following resources during each load stage.

Go application CPU

CPU saturation occurs when the application needs more processing time than the available CPU capacity can provide.

Use operating-system tools to inspect CPU consumption and pprof to identify expensive functions.

Consider a restaurant listing handler that repeatedly constructs large JSON responses. Under increasing traffic, JSON encoding and allocation work may consume a substantial portion of the available CPU.

A CPU profile can show whether the application is spending time in:

  • JSON encoding and decoding.
  • Authentication and validation.
  • Menu assembly.
  • Garbage collection.
  • Mutex contention.

A profile showing high network activity but little application CPU usage suggests that you should investigate dependencies and waiting time instead of optimizing JSON encoding.

The important measurement is not merely that CPU usage increased. Check whether CPU saturation coincides with rising latency and declining throughput.

MySQL connections and queries

MySQL can become the first bottleneck when queries take too long or the application cannot obtain available database connections.

Your Go application exposes pool statistics through db.Stats().

go
stats := db.Stats()

log.Printf(
    "open=%d in_use=%d idle=%d wait_count=%d wait_duration=%s",
    stats.OpenConnections,
    stats.InUse,
    stats.Idle,
    stats.WaitCount,
    stats.WaitDuration,
)

These values help distinguish an idle pool from one experiencing connection pressure.

A growing WaitCount means application operations have waited for a database connection. It does not automatically mean the pool needs a larger limit.

Slow queries or long transactions might be holding connections for too long.

Inspect active MySQL sessions:

sql
SHOW FULL PROCESSLIST;

Look for long-running queries, active sessions and connections waiting on locks.

Use EXPLAIN to investigate the expensive query. For example, the orders (user_id, created_at, id) index should support the order history access pattern.

Increasing the Go connection pool without checking MySQL's capacity can make the situation worse.

Connection-pool sizing

Connection-pool sizing is about choosing a limit that supports concurrent database work without overwhelming MySQL.

In the next exercise the API reads its open limit from DB_MAX_OPEN_CONNS with a bounded default, and the idle limit must never exceed the open limit.

A pool limit is a safety boundary, not a direct measurement of database capacity.

When sizing the pool, consider:

  1. The measured number of connections in use.
  2. The number of requests waiting for connections.
  3. Query and transaction duration.
  4. MySQL's configured connection limit.
  5. The total number of API instances and other database clients.

For example, if every API instance has its own connection pool, the total possible application connections are:

total API connections =
    application instances * maximum connections per instance

You must also account for workers, administrative connections and other services accessing MySQL.

A pool that appears safe for one API instance can exceed MySQL's capacity after the service scales horizontally.

Do not increase DB_MAX_OPEN_CONNS until you have checked whether the database can handle the additional concurrent queries.

Redis operations and cache behaviour

Redis can become the first bottleneck when the application sends more commands than Redis can process within the request latency budget.

A high Redis requests-per-second value is not automatically a problem. Measure command latency, throughput and memory usage alongside application latency.

The menu cache uses a cache-aside design. A cache hit serves the menu without loading it from the database. A cache miss requires the application to load the menu and populate the cache.

Cache hit rate

The cache hit rate measures the proportion of cache lookups that find the requested value.

The formula is:

cache hit rate = cache hits / total cache lookups

For example:

Cache hits:       950
Cache misses:      50
Total lookups:   1000

Cache hit rate = 950 / 1000 = 95%

A higher hit rate generally reduces the number of database reads needed for cached operations.

Consider the browse workload at 1,080 RPS with a 95% menu cache hit rate.

The estimated miss rate is:

miss rate = 1 - 0.95
          = 0.05

The estimated database query rate is:

1,080 * 0.05 = 54 queries per second

This calculation assumes that each cache miss produces one relevant database query.

If assembling a menu requires multiple queries, the database workload will be higher. Also account for restaurant-list queries and other database activity that the simple calculation excludes.

The cache hit rate is workload-dependent. A warmed local cache may produce very different results from a production cache with a larger restaurant catalogue and a different access distribution.

Redis memory and capacity

Redis capacity depends on the number of cached entries, the size of each entry and the additional memory required by Redis to manage its data structures.

Measure actual memory consumption under a representative workload.

The menu cache stores restaurant-specific values with TTL and jitter. The number of active menus and the sizes of those menu responses affect memory usage.

You should measure:

  • Redis memory consumption.
  • Number of cached keys.
  • Cache eviction activity.
  • Command latency.
  • Cache hit rate.

A Redis instance can have enough CPU capacity to process commands but still run out of memory.

Do not estimate Redis size from the number of restaurants alone. Menu sizes can vary considerably.

Network and load generator

The network can limit throughput even when CPU, MySQL and Redis have available capacity.

Large response payloads increase transfer time and network bandwidth requirements. High connection counts and retransmissions can also contribute to latency.

Measure network throughput and connection behaviour during the load test.

The load generator is another resource that needs attention.

Your laptop runs k6, the Go API, MySQL, Redis and Redpanda on shared hardware. These processes compete for CPU, memory, disk and network resources.

If k6 cannot generate the configured arrival rate, the reported throughput does not establish the backend's maximum capacity.

A benchmark can also become misleading when the load generator consumes most of the available CPU.

Choosing the next resource to scale

Once you have evidence of the first bottleneck, choose an improvement that addresses that resource.

Observed limitationPossible investigation
High application CPUProfile expensive functions, reduce unnecessary work or add application instances
MySQL connection waitsOptimize queries, reduce transaction duration and inspect database capacity
Redis latencyReduce unnecessary commands or investigate expensive operations
Network saturationInvestigate response payload sizes and available network capacity
Load generator saturationDistribute the load across additional generators

The first bottleneck can change after each improvement.

Suppose MySQL is initially limiting the service. After optimizing queries, application CPU might become the next constraint.

After adding application instances, Redis might become the bottleneck because those instances generate more cache commands.

Capacity planning is an iterative process. Fixing one resource does not mean the entire service has unlimited capacity.

Peak traffic and planning headroom

Average traffic is not sufficient for sizing a food-delivery service.

Demand changes throughout the day. Restaurant browsing and order placement can increase sharply around meal times.

The peak factor describes the relationship between peak traffic and average traffic.

peak factor = peak traffic / average traffic

For example, if average traffic is 500 RPS and peak traffic is 1,500 RPS:

peak factor = 1,500 / 500
            = 3

The service receives three times its average traffic at peak.

Use measured or observed traffic patterns when selecting the peak factor. Do not assume that every endpoint has the same factor. Restaurant browsing, checkout and order placement can have different traffic distributions.

Headroom

A service should not operate continuously at its measured maximum.

Headroom is the capacity margin you reserve between expected operating demand and the measured sustainable limit.

The margin protects against traffic variation, background jobs and resource failures.

A planning margin of 30% to 50% is a common starting point, depending on traffic variability and failure requirements. It is not a universal rule.

Consider a service that sustains 1,800 RPS while meeting its latency target.

Assume you reserve 40% headroom.

Measured sustainable rate = 1,800 RPS
Reserved headroom          = 40%
Usable capacity            = 60%

Planning rate = 1,800 * 0.60
              = 1,080 RPS

Use 1,080 RPS as the ordinary planning capacity per equivalent application tier under the same measured conditions.

This is different from claiming that the service can sustain only 1,080 RPS. The measured sustainable capacity is still 1,800 RPS. You are deliberately leaving part of that capacity unused during normal operation.

Worked capacity calculation

Consider a laptop running the Go API, worker, MySQL, Redis, Redpanda and k6.

The following measurements are illustrative. They show how to convert a load-test result into a planning estimate. They are not benchmark results or production guarantees.

Browse capacity

Suppose the browse test produces:

MeasurementResult
Completed throughput1,800 RPS
p95 latency120 ms
CPU utilization85%
Error rateWithin the accepted threshold
Cache hit rate95%

The measured sustainable rate is 1,800 RPS.

With 40% headroom:

Planning rate = 1,800 * (1 - 0.40)
              = 1,080 RPS

The application tier therefore has a planning rate of 1,080 RPS per equivalent tested capacity under these conditions.

Do not confuse the 85% CPU measurement with a universal CPU limit. It is evidence about this particular machine and workload.

MySQL query load

A 95% menu cache hit rate means that approximately 5% of relevant menu lookups miss the cache.

At the planning rate:

Browse planning rate = 1,080 RPS
Cache miss rate      = 5%

Estimated DB queries = 1,080 * 0.05
                     = 54 queries per second

This estimate assumes one database query for each relevant cache miss.

The actual query load can be higher because the API also handles restaurant listing, authentication and other operations.

Use measured query counts to validate this estimate.

Required application instances

Suppose the deployment needs to handle 6,000 browse requests per second at peak.

Each equivalent application tier has a planning capacity of 1,080 RPS.

The number of instances required for capacity is:

required instances = ceil(6,000 / 1,080)
                   = 6

You need six instances to meet the traffic requirement under the assumed scaling behaviour.

Add one additional instance for failure tolerance:

6 capacity instances + 1 spare instance = 7 instances

The resulting deployment has seven application instances.

This estimate assumes that each instance can independently sustain the tested planning rate and that shared dependencies can support the combined traffic.

Adding application instances does not automatically multiply MySQL or Redis capacity.

Database capacity across instances

Every application instance can create database connections through its own pool.

Suppose each instance has a configured maximum connection limit of 25 (an illustrative value).

With seven instances:

7 * 25 = 175 possible API connections

This is a possible connection total, not the number of connections that will always be open.

You must compare it with MySQL's available connection capacity and account for the worker and other clients.

The database sizing decision also depends on query throughput, transaction duration and write activity. A connection limit alone cannot establish how many queries MySQL can handle.

Order write throughput

The order workload measures order creation at a configured rate of 100 orders per second.

Assume each order causes approximately five MySQL row writes across order-related tables.

Orders per second = 100
Row writes/order  = 5

Estimated writes = 100 * 5
                 = 500 row writes per second

This is an estimate of order-related row writes, not the complete database workload.

The transactional outbox adds database work because the relay reads pending events and updates their delivery state.

You should measure actual writes, transaction duration and relay throughput before treating 500 row writes per second as a database sizing limit.

Consumer lag

The outbox relay publishes events to Kafka. The consumer processes those events after publication.

Consumer lag measures how far a consumer is behind the available messages.

A service can accept orders successfully while its event consumer falls behind. The order endpoint's response latency alone does not reveal this backlog.

Compare the rate at which messages arrive with the rate at which consumers process them.

For a stable workload, an approximate backlog recovery time is:

recovery time = consumer lag / processing rate

For example, if a consumer has 6,000 pending messages and processes 200 messages per second:

recovery time = 6,000 / 200
              = 30 seconds

This estimate assumes that new messages stop arriving and the processing rate remains stable.

If the arrival rate stays above the consumer's processing rate, the backlog continues growing. Increasing order API instances without considering consumer throughput can make this problem worse.

Watch the consumer lag for each relevant group and topic. The Kafka broker's capacity and the number of consumer workers also matter when planning write traffic.

Concurrency and Little's Law

Throughput and latency imply a level of request concurrency.

Little's Law relates average arrival rate, average time in the system and average concurrency.

L = λ * W

Where:

  • L is the average number of operations in progress.
  • λ is the arrival rate in operations per second.
  • W is the average time an operation takes in seconds.

Suppose the planning workload is 1,080 requests per second and average response time is 120 milliseconds.

Convert the response time to seconds:

120 ms = 0.120 seconds

Then:

L = 1,080 * 0.120
  = 129.6

Approximately 130 requests are in progress on average.

This calculation uses average latency, not p95 or p99.

Substituting p95 into Little's Law gives a rough comparison, not an exact concurrency estimate. The law uses average time in the system.

This calculation is useful when checking whether your measured concurrency and VU configuration are reasonable.

It also helps you understand why a system can need more concurrent capacity as request duration increases, even when the arrival rate remains unchanged.

Active-user estimation

Request concurrency and active users are different quantities.

One active customer can issue multiple requests during a browsing session. Some users may wait between requests, while others refresh frequently.

Suppose one active customer generates one request every six seconds on average.

Requests per active user = 1 / 6
                         = 0.1667 RPS

At 1,080 RPS:

Active users = 1,080 / 0.1667
             = approximately 6,480

The planning capacity corresponds to approximately 6,480 simultaneously active users under this assumed browsing pattern.

This is an estimate, not a measured user count.

The result changes when customers browse more restaurants, refresh more frequently, open multiple screens or place orders.

Use actual request patterns from application analytics when translating RPS into active users.

Storage estimation

Capacity planning also includes persistent storage.

Order volume affects the size of the orders table and its related records. Menu changes, order events and operational records also consume storage.

Storage estimation starts with the expected number of records and the average storage cost per record.

A basic daily estimate is:

daily storage =
    rows created per day * average bytes per row

For order storage, consider the related tables and indexes rather than estimating only the main orders table.

A more complete estimate includes:

  • Order rows.
  • Order line rows.
  • Outbox event rows.
  • Secondary indexes.
  • Database metadata and operational overhead.
  • Retained backups and replicas.

The storage required for retained data depends on the retention period:

retained storage =
    daily storage * retention days

This is a basic estimate. Actual storage also depends on row sizes, indexes, binary logs, backup compression and database configuration.

Do not invent an average row size when sizing production storage. Measure it from representative data.

Also consider growth. If order volume doubles, a storage estimate based on today's daily record count becomes outdated.

Comparing measured and estimated capacity

The theoretical estimates from Weeks 1 to 5 should now be compared with the measured results.

A difference between the two does not automatically mean the original estimate was wrong.

It may indicate that one of its assumptions did not match the implemented system.

Consider these examples:

Theoretical assumptionPossible measured difference
Every menu request reaches MySQLThe menu cache serves many requests
Every order creates a fixed number of writesOutbox and transaction operations add database activity
Redis commands have negligible latencyCommand latency increases under concurrent traffic
Each API instance scales independentlyShared MySQL capacity limits horizontal scaling
Each consumer processes events at a fixed rateConsumer lag increases as event production rises

Cache effects

The theoretical database estimate may assume that every menu request performs a database read.

The measured cache hit rate reduces that load.

However, a warm cache can make a local benchmark appear faster than a cold cache. Measure both cache behaviour and request latency when evaluating the result.

Query and transaction costs

A theoretical estimate may count one operation per request. The implementation can perform several SQL statements inside a transaction.

Order placement also interacts with idempotency and outbox processing.

Measure actual database query rates and transaction duration instead of treating order RPS as equivalent to database write throughput.

Shared resource limits

Adding application instances can increase aggregate request processing capacity while increasing load on shared dependencies.

For example, seven instances might handle more restaurant requests than one instance, but all seven still use the same MySQL database and Redis deployment.

The shared resource may saturate before the application tier.

Load-generator limits

Your local benchmark also includes the cost of generating traffic.

A laptop running k6 alongside MySQL, Redis, Redpanda and the Go services may become constrained before the API reaches its own limit.

The measured capacity then describes the shared development environment rather than the backend in isolation.

Move the load generator to separate hardware when you need to measure production-equivalent capacity.

Golden signals

The golden signals provide a compact way to understand service health during a load test.

They cover four areas:

SignalWhat to inspect
LatencyRequest duration, especially p95 and p99
TrafficRequests per second and order throughput
ErrorsFailed requests and unexpected response statuses
SaturationCPU, connection waits, Redis pressure and consumer lag

These signals work together.

A rising p99 with stable traffic and increasing database connection waits suggests a different problem from rising p99 with high CPU consumption.

Likewise, low HTTP errors do not prove that the outbox consumer is keeping up. You must check consumer lag separately.

Use these measurements to identify the first resource that prevents the service from meeting its latency and error targets.

Laptop measurements and production capacity

A local benchmark is useful for comparing implementation changes. It is not a direct prediction of production throughput.

Your laptop shares CPU, memory, disk and network resources between k6, the API, worker, MySQL, Redis and Redpanda.

A production deployment may use dedicated application instances and separately provisioned database, Redis and Kafka infrastructure.

The local result is therefore an upper bound on what that particular shared machine can demonstrate under those conditions. It is not a universal upper bound on the application's production capacity.

Distinguish three types of information:

Measured values

  • Completed RPS.
  • p95 and p99 latency.
  • Error rate.
  • CPU utilization.
  • Database connection waits.
  • Redis latency.
  • Consumer lag.

Estimated values

  • Production application instance count.
  • Expected active users.
  • Required database throughput.
  • Future traffic distribution.
  • Capacity under different hardware configurations.

Assumptions

  • Production cache hit rate.
  • Requests per user session.
  • Order volume distribution.
  • Failure behaviour.
  • Resource scaling behaviour.

Document which values belong to each category.

Repeat the benchmark at different load levels and durations. A short successful run does not establish sustained capacity.

Writing a capacity statement

A capacity statement is a concise, reproducible description of what the service can handle under specified conditions.

It connects the workload, latency target, resource limit and planning margin.

Include:

  • Hardware and environment used for testing.
  • Endpoint or workload being measured.
  • Sustainable request rate.
  • Measured p95 and p99 latency.
  • Latency targets and error rate.
  • Headroom applied.
  • First resource to saturate.
  • Database, Redis and Kafka assumptions.
  • Load-generator configuration.
  • Known limitations.

The statement should distinguish the measured sustainable rate from the lower planning rate after headroom.

For example, use this structure in your README:

On [hardware and environment], the [workload] sustains [N] requests per second at p95 latency below [X] ms and p99 latency below [Y] ms, with an error rate below [Z]%. We apply [H]% headroom, giving a planning capacity of [P] requests per second per instance. The first resource to saturate is [resource], observed through [measurement]. The result assumes [cache hit rate], [database configuration], [Redis configuration] and [load profile]. These measurements were repeated for [duration] using [load-generator configuration]. Production capacity must be validated on production-equivalent infrastructure.

Do not report a request rate without its latency target. Throughput without a service-quality requirement is an incomplete capacity result.

Capacity evidence for the next exercise

The exercise "Browse and order k6 scripts" establishes the before numbers for the restaurant and order workloads. The next exercise, "Find and fix the first bottleneck", uses the browse workload to investigate CPU usage, MySQL query plans and connection-pool activity before making a targeted change.

Use the measured p95, p99 and error rate to decide whether the service meets its workload targets. Combine those results with CPU profiles, pool gauges, Redis measurements and consumer lag to determine the first resource that needs attention.

After the change, rerun the same workload and compare the before numbers with the after numbers.

A lower p99 does not prove that the database pool change caused the improvement. Check whether the pool was saturated before the change and whether its wait counters support that explanation.

The final capacity statement should describe what your measurements establish, which assumptions remain unverified and what you would investigate next.

Check your understanding

Question 1 of 4

A browse endpoint sustains 1,500 RPS at p95 latency of 100 ms. At 1,700 RPS, p95 rises to 260 ms. The target is p95 below 150 ms. What is the highest demonstrated sustainable rate?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (k6, Go, MySQL, Redis).

Finished Lesson 6.10?