This article examines three scaling concerns: partition routing, connection reuse and request-rate controls.
The useful engineering question is not a population headline but a capacity question: what fails first when demand exceeds the assumptions in a design? Distinguish user counts, concurrent connections and operations per second before choosing a remedy.
There is no universal failure threshold at ten million users, connections or writes. These measure different workloads. The examples below illustrate mechanisms, not a validated capacity plan: none was compiled, executed, load-tested or deployed here.
The Illusion of the "Infinite Cloud"
Adding application instances does not automatically increase the capacity of every dependency. Diagnose bottlenecks under a representative workload rather than assuming that an autoscaler can remove them. Useful areas to investigate include:
- Database: connection budgets, lock contention, index access patterns and the working set relative to memory. A large table alone does not establish which is limiting throughput.
- Network: connection churn, available local/remote address pairs and limits in NAT, proxies or stateful firewalls.
- Application: CPU, allocation pressure, blocking work, queue growth and scheduling delays. Measure their contribution instead of assuming a language runtime is the cause.
The following patterns address particular bottlenecks. They do not remove finite CPU, memory, storage or network capacity.
1. Database scaling: partitioning and routing
A single database may or may not meet a workload, regardless of registered-user count. Read replicas can move some read work but introduce consistency and routing considerations. Partitioning is one possible response to a measured write bottleneck, not a mandatory consequence of crossing a round number.
Partitioning choices affect transaction boundaries, placement, replication and recovery. Shared-nothing designs distribute resources among nodes, but do not automatically balance a hot key or eliminate coordination. Product-specific database designs require their own review; the code here is only a routing illustration.
Designing a Consistent Hashing Ring in Go
Consistent hashing maps keys to positions in a ring so that a membership change need not remap every key. This is a routing property, not an implementation of database migration, re-indexing or transaction consistency.
This unexecuted Go example builds an immutable routing snapshot from bounded node identifiers. It rejects duplicate identifiers and hash-position collisions rather than silently replacing an owner. It does not connect to a database.
package routingdemo
import (
"crypto/sha256"
"encoding/binary"
"fmt"
"sort"
"strconv"
)
type entry struct { position uint64; node string }
type Ring struct { entries []entry }
func position(s string) uint64 {
sum := sha256.Sum256([]byte(s))
return binary.BigEndian.Uint64(sum[:8])
}
func validNode(s string) bool {
if len(s) == 0 || len(s) > 64 { return false }
for _, c := range s {
if !((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-') {
return false
}
}
return true
}
func NewRing(nodes []string, virtual int) (*Ring, error) {
if len(nodes) == 0 || len(nodes) > 128 || virtual < 1 || virtual > 256 {
return nil, fmt.Errorf("invalid bounded ring dimensions")
}
seenNodes := make(map[string]bool)
seenPositions := make(map[uint64]bool)
r := &Ring{entries: make([]entry, 0, len(nodes)*virtual)}
for _, node := range nodes {
if !validNode(node) || seenNodes[node] {
return nil, fmt.Errorf("invalid or duplicate node")
}
seenNodes[node] = true
for i := 0; i < virtual; i++ {
p := position("node\x00" + node + "\x00" + strconv.Itoa(i))
if seenPositions[p] { return nil, fmt.Errorf("hash-position collision") }
seenPositions[p] = true
r.entries = append(r.entries, entry{p, node})
}
}
sort.Slice(r.entries, func(i, j int) bool {
return r.entries[i].position < r.entries[j].position
})
return r, nil
}
func (r *Ring) Lookup(key string) (string, error) {
if r == nil || len(r.entries) == 0 || len(key) == 0 || len(key) > 128 {
return "", fmt.Errorf("invalid ring or key")
}
p := position("key\x00" + key)
i := sort.Search(len(r.entries), func(i int) bool {
return r.entries[i].position >= p
})
if i == len(r.entries) { i = 0 }
return r.entries[i].node, nil
}
// No mutation API, database access, migration, replication or claimed output.
Virtual positions can improve distribution across many keys, but no fixed count guarantees balanced bytes, request load or hot keys. This snapshot has no membership-update protocol, data migration, replication or failover. Readers can share an unchanged snapshot after safe publication; replacing it still needs application-level coordination.
2. Overcoming Network Bottlenecks: Ephemeral Port Exhaustion
A service making many outbound calls may encounter cannot assign requested address. Treat that as a diagnostic clue, not proof of port exhaustion: inspect address configuration, connection behavior and intermediary limits in the actual environment.
TCP identifies a connection by its two address/port endpoints, not a local port alone. TIME_WAIT protects against delayed segments after certain closure paths; it does not mean every closed connection blocks that local port for every destination. Port ranges, wait timing and permitted reuse depend on the operating system and connection state. Do not apply universal port-count or sysctl recipes.
Connection reuse and bounded concurrency
Create one shared client/transport per relevant configuration, not one per request. This unexecuted builder clones the standard transport and keeps HTTP/2 negotiation enabled; its small budgets are examples, not capacity recommendations. TCP keepalive probes detect idle-peer problems; they are not HTTP connection reuse. No network request is made by this snippet.
package httpdemo
import (
"fmt"
"io"
"net"
"net/http"
"time"
)
func NewDemoClient() (*http.Client, error) {
base, ok := http.DefaultTransport.(*http.Transport)
if !ok { return nil, fmt.Errorf("default transport was replaced") }
tr := base.Clone()
tr.DialContext = (&net.Dialer{
Timeout: 3 * time.Second, KeepAlive: 30 * time.Second,
}).DialContext
tr.ForceAttemptHTTP2 = true
tr.MaxConnsPerHost = 32 // Dialing, active and idle connections.
tr.MaxIdleConns = 64
tr.MaxIdleConnsPerHost = 16
tr.IdleConnTimeout = 60 * time.Second
tr.TLSHandshakeTimeout = 5 * time.Second
tr.ResponseHeaderTimeout = 5 * time.Second
return &http.Client{
Transport: tr, Timeout: 10 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}, nil
}
func ReadBounded(resp *http.Response, max int64) ([]byte, error) {
if resp == nil || resp.Body == nil { return nil, fmt.Errorf("missing body") }
defer resp.Body.Close()
if max < 1 || max > 1<<20 { return nil, fmt.Errorf("invalid byte limit") }
data, err := io.ReadAll(io.LimitReader(resp.Body, max+1))
if err != nil { return nil, err }
if int64(len(data)) > max { return nil, fmt.Errorf("response too large") }
return data, nil
}
// Builder and bounded-reader definitions only. No URL, request or runtime result.
MaxIdleConnsPerHost limits idle connections, not active demand. The separate active-connection limit is per host, not a global request limit; HTTP/2 can multiplex requests. Reuse also depends on the server and reading a body to EOF before closing it. The bounded reader deliberately closes oversized bodies rather than draining unbounded data, so that connection may not be reused. Add separate request/queue budgets and review destinations and proxy policy. Nothing here bypasses OS limits.
3. Rate limiting: a fixed window starting at the first request
Rate limits can constrain some abusive or accidental demand, but are not a complete DDoS defense. Use layered admission controls, bounded queues and an explicit overload policy; a request that reaches Redis has already consumed upstream resources.
Redis can serialize a short Lua check-and-update operation on the server handling the key. Script execution blocks other work there, so keep scripts bounded. Atomic execution does not establish persistence, availability, rollback of every runtime error or a globally durable rate guarantee.
A bounded Redis/Go teaching example
The following unexecuted example permits at most a configured count during a key’s one-second lifetime. It is not a token bucket or a rolling-window bound: requests can cluster around expiry. Only two synthetic principal IDs are accepted, so callers cannot create arbitrary keys. A real integration must derive an opaque principal from trusted authentication, not a body field, raw IP address or API key. Supply a separately reviewed client with ACL/TLS, finite connection/pool/read/write timeouts, context deadlines enabled and command retries disabled (configure MaxRetries: -1 before client creation). No client is created or connected here.
package limitdemo
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
const fixedWindowLua = `
local limit = tonumber(ARGV[1])
if not limit or limit < 1 or limit > 1000 or limit ~= math.floor(limit) then
return redis.error_reply('invalid limit')
end
local value = redis.call('GET', KEYS[1])
if not value then
redis.call('SET', KEYS[1], 1, 'PX', 1000)
return 1
end
local count = tonumber(value)
if not count or count < 1 or count ~= math.floor(count) then
return redis.error_reply('invalid counter')
end
if redis.call('PTTL', KEYS[1]) <= 0 then
return redis.error_reply('invalid expiry')
end
if count >= limit then return 0 end
redis.call('INCR', KEYS[1])
return 1
`
type DemoLimiter struct { client *redis.Client; limit int }
// rdb must satisfy the separately reviewed client contract in the text.
// This constructor does not create a client or contact a server.
func NewDemoLimiter(rdb *redis.Client, limit int) (*DemoLimiter, error) {
if rdb == nil || limit < 1 || limit > 1000 {
return nil, fmt.Errorf("invalid demo configuration")
}
return &DemoLimiter{client: rdb, limit: limit}, nil
}
func (l *DemoLimiter) Allow(ctx context.Context, principal string) (bool, error) {
if l == nil || l.client == nil || ctx == nil {
return false, fmt.Errorf("invalid limiter context")
}
// Fixed synthetic IDs only; never raw user input or credentials.
if principal != "demo-a" && principal != "demo-b" {
return false, fmt.Errorf("unknown demo principal")
}
callCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel()
result, err := l.client.Eval(callCtx, fixedWindowLua,
[]string{"demo:fixed-window:" + principal}, l.limit).Result()
if err != nil { return false, fmt.Errorf("limiter unavailable: %w", err) }
n, ok := result.(int64)
if !ok || (n != 0 && n != 1) {
return false, fmt.Errorf("unexpected limiter result")
}
return n == 1, nil
}
// No client initialization, invocation, live identities or claimed test output.
Concurrent script calls on the same key do not interleave their checks and increments. This assumes one protected namespace and consistent configuration. Eviction, restart, failover, lost writes or independent Redis authorities can reset counts. A timeout can leave the update outcome unknown; do not blindly retry. Here errors deny admission and must be handled as service unavailability, distinct from an ordinary limit rejection; do not expose internal Redis errors. Production authentication, global capacity, retention, recovery and overload handling remain outside the example.
Conclusion
Scaling starts with a measured constraint and a defined service objective. Route partitioned work deliberately, reuse connections within budgets and decide what to reject or defer when capacity is exhausted.
These mechanisms are starting points for design review, not evidence that a system supports ten million users. Capacity and failure testing with synthetic data, recovery planning and version-specific review are still required before any production adoption.
Which bottleneck would you measure first? Share nonsensitive design observations only; omit production logs, customer identifiers, endpoints and credentials.
End of article.
Primary references
- Original consistent-hashing paper
- Go SHA-256 API
- Go binary encoding API
- Go sorting and search API
- TCP specification: RFC 9293
- Linux IP configuration reference
- Go HTTP transport and client API
- Go network dialer API
- Go bounded I/O API
- Redis counter and rate-limit patterns
- Redis Lua execution semantics
- go-redis client options
- Redis Go client connection guidance