Capacity estimation

Estimate connection, Redis and network load for a target rider fleet, then take those assumptions into the Week 6 load tests.

Learning outcomes

  • Calculate normal and rate-limited location update rates from the number of online riders.
  • Estimate Redis command rates, including the location rate-limit check and active-delivery publications.
  • Budget connection memory, goroutines and file descriptors for an API instance.
  • Distinguish location publications from user-channel fan-out and estimate customer-facing bandwidth.
  • Identify likely bottlenecks and define the measurements needed to validate the capacity estimate.

Suppose one api instance must keep 20,000 customer connections and 5,000 rider connections open during the dinner peak. Redis must store the riders' positions, enforce the location update limit and distribute messages. You need to estimate whether the API instance or Redis reaches its limit first, before you test the system under load.

This is Capacity estimation: using the workload and resource costs to form a capacity target. The result is not a production guarantee. It is a set of assumptions that you can measure and revise.

The workload model

Start with one api instance and one Redis primary. Use the following workload throughout the calculation:

  • 5,000 riders are online.
  • 20,000 customers have active orders and maintain connections.
  • 80% of online riders have orders in the PICKED_UP state.
  • One customer watches each PICKED_UP delivery.
  • Each rider sends a location update every 4 seconds.
  • The API accepts at most one location update per rider every 2 seconds.

The 80% assumption gives you 4,000 riders carrying PICKED_UP orders:

5,000 * 0.80 = 4,000 active deliveries

Those 4,000 customers receive location updates. The other 16,000 connected customers can still receive order events through their WebSocket connections. They do not automatically receive location messages.

This distinction matters. The number of connected customers determines connection and memory requirements. The number of customers watching PICKED_UP deliveries determines the location message workload.

For this example, assume one connection per customer and one connection per online rider. The API therefore maintains:

20,000 + 5,000 = 25,000 WebSocket connections

Keep these assumptions visible. If customers use multiple devices, riders maintain multiple connections, or several customers watch one delivery, the connection and message counts change.

Location update rate

A rider sends one location update every 4 seconds while online. The normal arrival rate depends on the number of online riders and their update interval.

For 5,000 online riders:

5,000 / 4 = 1,250 location updates per second

The API receives approximately 1,250 location update requests per second under the normal workload.

This calculation assumes that riders distribute their updates evenly over time. Real traffic can arrive in bursts. Phones may reconnect together after losing network coverage, and several clients may send an update at nearly the same moment.

The backend must enforce its own limit because the mobile app does not control what reaches the API. Each rider has a Redis key named rider:loc:{id}. The API creates that key with NX and a 2-second expiry before processing the location update.

A simplified check looks like this:

go
allowed, err := rdb.SetNX(
    ctx,
    "rider:loc:"+riderID,
    "1",
    2*time.Second,
).Result()
if err != nil {
    return err
}
if !allowed {
    return nil
}

The key is created only when it does not already exist. A second request from that rider during the 2-second window cannot create the key, so the API rejects or discards that update instead of processing it.

The server-side limit permits at most one accepted update every 2 seconds per rider. Its theoretical accepted update rate is:

1 / 2 = 0.5 accepted updates per second per rider

For 5,000 riders:

5,000 / 2 = 2,500 accepted updates per second

You now have two workload figures:

WorkloadLocation updates per second
Normal clients sending every 4 seconds1,250
Cooperative clients sending at the 2-second limit2,500

The second figure is the maximum accepted update rate under this model. It does not mean the API can receive only 2,500 requests per second. The API still has to check every incoming request against the Redis limit.

For example, suppose every rider sends an update every 500 milliseconds. That creates 10,000 incoming requests per second:

5,000 / 0.5 = 10,000 attempts per second

The 2-second limit still permits only 2,500 accepted updates per second. The other requests are rejected, but their rate-limit checks still consume resources.

A location update is useful only if it reflects a recent position. Queueing rejected updates for later processing would make the customer's map display stale positions. Reject them instead.

Redis command rate

An accepted location update performs several Redis operations. Count the rate-limit check as well as the work that follows an accepted check.

The operations are:

  1. SET NX on rider:loc:{id} with a 2-second expiry to enforce the per-rider limit.
  2. GEOADD on riders:online to update the rider's coordinates.
  3. SET on rider:seen:{id} with a 15-second TTL to refresh the seen key.
  4. PUBLISH on order:{id}:loc when the rider's order is PICKED_UP.

The first operation runs for every incoming request. The next two run only after the rate-limit check accepts the request. The publication also requires a PICKED_UP order.

For the normal workload, assume all 5,000 online riders send one update every 4 seconds. The rate-limit check accepts each update because the interval is longer than 2 seconds.

Rate-limit checks

1,250 SET NX commands per second

GEOADD

1,250 commands per second

Seen-key refreshes

1,250 SET commands per second

Location publications

Only 80% of the riders have PICKED_UP orders:

1,250 * 0.80 = 1,000 PUBLISH commands per second

The total Redis command rate is:

1,250 + 1,250 + 1,250 + 1,000 = 4,750 commands per second

Now consider cooperative clients sending at the 2-second limit. All 2,500 requests per second pass the rate-limit check, so each accepted update runs the remaining operations.

OperationCommands per second
Rate-limit SET NX2,500
GEOADD2,500
Seen-key SET2,500
Location PUBLISH2,000
Total9,500

The publication rate remains 80% of the accepted update rate:

2,500 * 0.80 = 2,000 PUBLISH commands per second

The 2-second limit therefore caps the normal location-processing work at 2,500 accepted updates per second. It does not cap the number of rate-limit checks when clients send more requests than that.

Consider the 500-millisecond example again. Its 10,000 incoming requests per second each need a SET NX check. Only 2,500 requests are accepted, so the other operations run at the accepted update rates.

The total becomes:

10,000 + 2,500 + 2,500 + 2,000 = 17,000 commands per second

This is why you must separate incoming request rate from accepted update rate when estimating Redis load.

For a rough reference, assume one Redis primary can process around 100,000 simple commands per second on suitable hardware. The normal workload's 4,750 commands per second is approximately 4.75% of that reference. The cooperative limit-saturating workload's 9,500 commands per second is approximately 9.5%.

These percentages are comparisons, not capacity guarantees. The workload contains more than simple key-value commands. GEOADD maintains an indexed geographic data structure and has O(log N) complexity for an individual addition, where N is the number of indexed members. PUBLISH also has work associated with delivering messages to subscribers.

The worker adds another kind of Redis work during order assignment. It searches within 5 km for at most five riders, then attempts one claim with SET order:{id}:claim NX PX 30000. The claim allows one rider to hold the 30-second offer. These operations happen during assignment, not for every location update, so do not add them to the sustained location-update total without an assignment rate.

Connection memory

A WebSocket connection stays open while the customer or rider needs live updates. Unlike an HTTP request, it continues to consume resources after the server has sent a response.

The example workload has 25,000 connections. Each connection has one buffered send channel and two goroutines: a reader and a writer.

A goroutine has its own stack. For a rough estimate, assume an initial stack of 2 to 8 KiB per goroutine. Two goroutines therefore account for:

2 * 2 to 8 KiB = 4 to 16 KiB per connection

That is only part of the cost. You must also account for the WebSocket library's buffers and state, the connection's hub registration, the send channel and its queued messages, and other application objects.

The send channel is buffered so a slow phone does not block every sender. In this project, each connection has a bounded send channel with 32 slots. If each slot stores a message pointer, the channel's pointer storage is approximately:

32 * 8 bytes = 256 bytes

The channel's storage is not the whole cost of queued messages. The messages themselves and any objects they reference also occupy memory.

A full send channel drops the message rather than blocking the sender. This keeps a slow client from causing unbounded queue growth or stopping other connections from receiving messages. The trade-off is that the client may miss an update. The sender must not assume every message reaches the phone.

For capacity planning, use an estimate of 20 to 40 KiB per connection. This is a working estimate for the application, not a fixed memory cost guaranteed by Go or the WebSocket library. It includes the goroutines, buffers, channel, connection state and hub bookkeeping.

This is Memory per connection: the memory required to keep a persistent connection alive, including the resources associated with it.

Calculate the total for 25,000 connections.

At 20 KiB per connection:

25,000 * 20 KiB = 500,000 KiB

That is approximately 488 MiB.

At 40 KiB per connection:

25,000 * 40 KiB = 1,000,000 KiB

That is approximately 977 MiB.

The estimated connection-related memory is therefore about 488 to 977 MiB.

A connection budget does not include the entire API process. The process also needs memory for the application heap, MySQL and Redis clients, request handling, caches, logging and other allocations. Go's garbage collector and temporary allocations also affect the process's memory use.

For this workload, start with one API server with 4 GiB of RAM. That gives the process room beyond the estimated connection cost, but it does not prove that the server can maintain 25,000 connections under every traffic pattern. CPU use, allocation rates, message queues and actual library buffers can change the result.

File descriptor limits

Every accepted TCP connection uses a file descriptor on the API server. A file descriptor is an operating system identifier for an open resource, such as a socket or file.

Linux processes have a limit on the number of file descriptors they can open. This is the File descriptor limit.

You can inspect the current shell's soft limit with:

bash
ulimit -n

Suppose the process has a limit of 1,024. That is far below the 25,000 descriptors needed for the example's WebSocket connections alone.

The API also needs descriptors for its listening socket, Redis connections, MySQL connections, logs and other open resources. Reserve another 1,000 descriptors for these resources and operational overhead.

The estimated requirement is:

25,000 + 1,000 = 26,000 descriptors

A process limit of 65,536 gives this example reasonable headroom. It is not enough to change the shell's setting and assume the whole system can support that number. The process configuration and the operating system's limits must both permit the workload.

The API should also reuse its Redis and MySQL connections. Opening new outbound connections for every location update would add unnecessary resource usage and connection churn.

Ephemeral ports are a separate concern. A machine uses an ephemeral local port when it initiates an outbound TCP connection. The 25,000 accepted client connections do not each consume a separate outbound ephemeral port on the API server. They consume accepted sockets and file descriptors. The clients have their own outbound connection ports.

Ephemeral port exhaustion becomes relevant when the API initiates very large numbers of outbound connections, especially to the same destination, or repeatedly creates connections instead of reusing them. Reuse the Redis and MySQL clients rather than creating a connection for each request.

Pub/Sub fan-out

A message published to Redis can reach multiple subscribers. This distribution is called Pub/sub fan-out across instances.

There are two channel patterns to keep separate in this project.

Location updates for a PICKED_UP order are published to its order:{id}:loc channel. The normal workload produces 1,000 of these publications per second. The limit-saturating workload produces 2,000 per second under the same 80% active-delivery assumption.

Order events reach users through the Redis user channel user:{id}. Every api instance holds one PSUBSCRIBE user:* subscription. The subscription matches user channels, not the order-specific location channels.

That distinction affects how you calculate fan-out. A publication to user:42 matches the pattern subscription on every api instance. Each instance receives a copy, even though only one instance may own the local WebSocket connection for user 42.

Suppose you run three api instances. One order event published to user:42 produces three subscriber deliveries:

1 publication * 3 api instances = 3 subscriber deliveries

The hub on each instance checks its local connections. Only the instance with a connection for user 42 can forward the event to that connection. The other instances have no matching local connection and do not deliver it to another user.

If the system publishes E user-channel events per second and runs A api instances, the pattern subscriptions perform:

A * E subscriber deliveries per second

The actual order-event rate is not specified by this workload, so you cannot produce a trustworthy numerical total for it. You can still use the formula when Week 6 measurements provide the event rate.

Do not apply that multiplier automatically to the 1,000 location publications per second. Those messages use order:{id}:loc, while the stated pattern subscription matches user:*. The number and placement of location-channel subscribers depend on the tracking subscription design. Without that information, multiplying location publications by the number of api instances would invent additional work.

For the location workload, assume one customer watches each active delivery. Each location publication has one intended customer recipient. If more than one authorized customer or device watches an order, the number of client deliveries increases with the number of recipients.

The PSUBSCRIBE user:* subscription is one long-lived subscription per api instance, not one subscription per user. A single subscription can receive messages for many users. This keeps subscription count separate from the number of connected customers.

This architecture trades extra message delivery between Redis and api instances for simpler routing. As the number of api instances grows, each instance receives copies of user events it may not need. A more selective routing design could reduce those deliveries, but it would require additional routing state or coordination.

Network bandwidth

A location update sent to a customer consumes network bandwidth. Estimate the size of the message that the customer receives, not the number of connected customers.

The published location payload contains {lat, lng}. For the example coordinates, the JSON representation is small:

json
{"lat":28.6139,"lng":77.2090}

Use approximately 29 bytes for this JSON payload. A small server-to-client WebSocket frame adds about 2 bytes of framing overhead. Round the combined payload and frame estimate up to 32 bytes per delivered location message.

At the normal rate, 1,000 active-delivery updates are published every second. Under the one-customer-per-active-delivery assumption, the aggregate client-facing payload estimate is:

1,000 * 32 = 32,000 bytes/second

That is approximately 32 KB/s, or 0.256 Mbps.

At the cooperative limit-saturating rate, 2,000 active-delivery publications per second produce:

2,000 * 32 = 64,000 bytes/second

That is approximately 64 KB/s, or 0.512 Mbps.

These are aggregate location-message estimates across the connections receiving the updates. If one api instance serves all those customer connections, it sends the full aggregate. If several instances share the customers, each instance sends the messages for its local connections. The total client-facing payload remains approximately the same when every update has one recipient.

This estimate excludes TCP and IP headers, TLS overhead, acknowledgements, heartbeat frames, connection establishment and unrelated application traffic. It also excludes Redis-to-subscriber traffic and the order-event stream, whose message sizes and rates are not specified here.

The bandwidth changes if several customers watch the same delivery. For example, with two recipients per active delivery, each location publication produces two client-facing messages. Multiply the output message rate by the number of recipients rather than by the number of all connected customers.

The location payload is small in this example. That does not make bandwidth irrelevant. A high update frequency, several recipients per order, or a larger message format can increase traffic. Measure actual bytes sent rather than treating the payload estimate as a network capacity guarantee.

Bottleneck analysis

The estimates now describe the main sustained resources for one api instance and one Redis primary.

ResourceNormal workloadCooperative limit-saturating workload
Online riders5,0005,000
Connected customers20,00020,000
WebSocket connections25,00025,000
Incoming location attempts1,250/s2,500/s
Accepted location updates1,250/s2,500/s
Redis commands, including rate checks4,750/s9,500/s
Location publications1,000/s2,000/s
Connection-related memory488 to 977 MiB488 to 977 MiB
Client-facing location payload32 KB/s aggregate64 KB/s aggregate

The rate-limited workload assumes cooperative clients send once every 2 seconds. Clients sending faster increase incoming attempts and rate-limit checks, even though accepted location updates remain capped.

The API's connection resources are likely to become an initial bottleneck in this example. Maintaining 25,000 connections requires substantial memory and 25,000 file descriptors before you account for the rest of the process. A low process descriptor limit can prevent the API from accepting the target number of connections, even when CPU and Redis still have capacity.

The API also has to run the reader and writer goroutine for every connection, manage hub registration, handle message queues and clean up closed connections. These operations consume CPU and memory in addition to the connection estimate.

Redis appears less constrained by the simple-command reference in this workload. The normal estimate is 4,750 commands per second, and the cooperative limit-saturating estimate is 9,500. Both are below the rough 100,000-command reference. However, geographic operations and Pub/Sub delivery can have different costs from simple commands. Redis latency, CPU, memory and network use still need measurement.

The user-channel pattern subscription also creates work that the location command totals do not capture. Every order event published to user:{id} reaches every api instance's PSUBSCRIBE user:* subscription. As you add api instances, this aggregate delivery work grows with the instance count. Measure it separately from location publications.

The first bottleneck is therefore a hypothesis, not a conclusion. Slow clients, garbage collection, CPU saturation, database contention, expensive geographic searches or a burst of rejected location requests can change which resource reaches its limit first.

Capacity target

Use this deployment as the starting point for the Week 6 load test:

  • One API server with 4 vCPUs and 4 GiB RAM.
  • One Redis primary with 2 vCPUs and 4 GiB RAM.
  • One api instance holding 25,000 concurrent WebSocket connections.
  • An estimated 20 to 40 KiB of connection-related memory per connection.
  • A process file descriptor limit of 65,536.
  • Approximately 1,000 descriptors reserved for non-WebSocket resources and operational overhead.
  • One customer connection per customer with an active order.
  • One rider connection per online rider.
  • A 4-second normal location update interval.
  • A server-side limit of one accepted location update per rider every 2 seconds.
  • Approximately 80% of online riders carrying PICKED_UP orders.
  • One customer receiving location updates per active delivery.
  • One PSUBSCRIBE user:* subscription per api instance.
  • Approximately 100,000 simple Redis commands per second as a rough reference, not a mixed-workload benchmark.

Under these assumptions, the initial target for one API instance is 5,000 online riders and 20,000 connected customers. That produces 25,000 concurrent connections, an estimated 488 to 977 MiB of connection-related memory and approximately 26,000 required file descriptors including the reserved overhead.

The initial target for one Redis primary is the workload generated by those 5,000 online riders and 4,000 active deliveries. It handles approximately 4,750 commands per second at the normal update interval, or 9,500 commands per second when cooperative clients send at the 2-second limit. Faster incoming attempts increase the rate-limit check count beyond those figures.

Treat these numbers as a starting capacity target, not a universal maximum. They assume that the API and Redis are otherwise lightly loaded and that the system's memory, CPU, descriptor use and latency stay within acceptable limits.

Validation in Week 6

The Week 6 load test replaces these assumptions with measurements. Start with a smaller number of simulated riders and customers, then increase both gradually. Keep the location update interval and the server-side limit in the test so you can compare measured rates with the estimates.

Measure at least:

  • Active WebSocket connections and connection failures.
  • API memory, CPU usage and goroutine count.
  • Open file descriptors and the configured process limit.
  • Incoming location requests and accepted location updates per second.
  • Redis command throughput and command latency.
  • Redis geographic operation latency.
  • Location publications and subscriber deliveries per second.
  • User-channel Pub/Sub deliveries across api instances.
  • WebSocket write failures and dropped messages.
  • Message delivery latency from rider to customer.

Run a normal workload first. Then increase the location request rate until the server-side limit rejects updates, and observe whether Redis command traffic still grows because of the extra checks. Also test slow clients so you can confirm that a full send channel drops messages instead of blocking other senders.

When the system fails below the estimated target, inspect the resource that reached its limit. Check the memory profile, goroutine count, descriptor usage and hub behaviour before increasing server size. If Redis latency rises first, inspect the geographic operations, write rates and subscriber delivery work rather than relying on the simple-command reference.

The estimate gives you a testable hypothesis. The load test tells you whether the API instance and Redis can sustain it.

Check your understanding

Question 1 of 4

The API has 5,000 online riders. Each phone sends a location update every 4 seconds, but the server accepts at most one update per rider every 2 seconds. Under normal client behaviour, how many location update requests should reach the API per second?

Pick an answer, then say how sure you are.

References

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

Finished Lesson 5.14?

Live capacity planning

1 items

  • 5.14Capacity estimationnot completed

Live order extensions

Up next · Module 6 · 3 items · about 2 h

Start module 6