blog.devgenius.io 5 min read Original Source

The scaling bottleneck nobody mentions in Go microservices

You ship your Go microservice. It handles 100 requests per second with ease.

Latency is flat, goroutines are well-behaved, and the dashboard looks healthy. Your team ships faster. You add more services. Everything is fine — until it isn’t.

At some point, something you never profiled becomes the thing that takes you down. Not your hot path, not your goroutine pool, not even your database.

It’s your connection management — specifically, the gap between how Go developers think about connections and how connections actually behave under load.

The hidden contract in net/http

Most Go services use net/http either directly or through a framework that wraps it. The default http.Client has a Transport under the hood — specifically, http.DefaultTransport. Most engineers never touch it, and that’s the first mistake.

Here’s what http.DefaultTransport gives you out of the box:

transport := &http.Transport{
    MaxIdleConns:        100,
    MaxIdleConnsPerHost: 2,  // ← this one will hurt you
    IdleConnTimeout:     90 * time.Second,
}
transport := &http.Transport{
    MaxIdleConns:        100,
    MaxIdleConnsPerHost: 2,  // ← this one will hurt you
    IdleConnTimeout:     90 * time.Second,
}

That MaxIdleConnsPerHost: 2 is doing a lot of damage in production systems that nobody is aware of.

If your service calls another service at high concurrency, most of your goroutines are going to be spending time establishing new TCP connections instead of reusing idle ones.

Every new connection means a full TCP handshake. For TLS services, add another round-trip or two.

You won’t see this in your p50. You’ll see it in your p99.

However, the fix is embarassingly simple:

client := &http.Client{
    Transport: &http.Transport{
        MaxIdleConns:        1000,
        MaxIdleConnsPerHost: 100,
        IdleConnTimeout:     90 * time.Second,
        DialContext: (&net.Dialer{
            Timeout:   5 * time.Second,
            KeepAlive: 30 * time.Second,
        }).DialContext,
    },
    Timeout: 10 * time.Second,
}
client := &http.Client{
    Transport: &http.Transport{
        MaxIdleConns:        1000,
        MaxIdleConnsPerHost: 100,
        IdleConnTimeout:     90 * time.Second,
        DialContext: (&net.Dialer{
            Timeout:   5 * time.Second,
            KeepAlive: 30 * time.Second,
        }).DialContext,
    },
    Timeout: 10 * time.Second,
}

But the real lesson is not the fix. It’s that this default exists at all, and that most production Go services are running with it unchanged.

Connection pools aren’t free

Go developers often reach for database/sql for PostgreSQL, initialize a connection pool with db.SetMaxOpenConns, and move on. The pool is there, so the problem is solved — right?

Not quite. The problem shifts.

When your service scales horizontally and you go from 3 instances to 30, your database suddenly has 30× the connection pressure.

PostgreSQL has a hard ceiling on connections. Typically you’re working with max_connections = 100 on a small instance, and max_connections = 500 on a beefier one. A naive horizontal scale can exhaust this instantly.

This is where PgBouncer or connection pooler sidecars become necessary infrastructure — but most teams add them reactively, after an outage, not proactively.

The tooling exists, but the mental model of “the pool is in the app” breaks down the moment you deploy more than a handful of replicas.

The deeper issue: Go’s database/sql pool is per-process. It doesn’t know about other processes. You need a layer above it that does.

// What most engineers write
db, _ := sql.Open("pgx", dsn)
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(10)
db.SetConnMaxLifetime(5 * time.Minute)

// What they don't account for:
// 10 pods × 25 max connections = 250 connections to Postgres
// 50 pods × 25 max connections = 1250 connections to Postgres
// (exceeds max_connections on most default configs)
// What most engineers write
db, _ := sql.Open("pgx", dsn)
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(10)
db.SetConnMaxLifetime(5 * time.Minute)

// What they don't account for:
// 10 pods × 25 max connections = 250 connections to Postgres
// 50 pods × 25 max connections = 1250 connections to Postgres
// (exceeds max_connections on most default configs)

The fix isn’t just tuning the numbers. The fix is acknowledging the per-process scope of the pool and planning for it across your deployment topology.

The gRPC Thundering Herd

If you’re building internal microservices in Go, you’re almost certainly using gRPC. And gRPC has its own trap.

gRPC multiplexes all RPCs over a single HTTP/2 connection per backend. This is a feature — fewer connections, better resource usage. But it creates a sharp edge when services restart or when a backend becomes temporarily unavailable.

When the connection drops, all in-flight RPCs fail simultaneously. All callers retry simultaneously. This is the thundering herd, and gRPC gives it to you for free unless you configure keepalives, backoff, and retry policies thoughtfully.

conn, err := grpc.NewClient(
    target,
    grpc.WithKeepaliveParams(keepalive.ClientParameters{
        Time:                10 * time.Second,
        Timeout:             5 * time.Second,
        PermitWithoutStream: true,
    }),
    grpc.WithConnectParams(grpc.ConnectParams{
        Backoff: backoff.Config{
            BaseDelay:  100 * time.Millisecond,
            Multiplier: 1.6,
            Jitter:     0.2,
            MaxDelay:   5 * time.Second,
        },
    }),
)
conn, err := grpc.NewClient(
    target,
    grpc.WithKeepaliveParams(keepalive.ClientParameters{
        Time:                10 * time.Second,
        Timeout:             5 * time.Second,
        PermitWithoutStream: true,
    }),
    grpc.WithConnectParams(grpc.ConnectParams{
        Backoff: backoff.Config{
            BaseDelay:  100 * time.Millisecond,
            Multiplier: 1.6,
            Jitter:     0.2,
            MaxDelay:   5 * time.Second,
        },
    }),
)

Jitter is not optional. Without it, a fleet restart causes every caller to retry at the same interval, and you recreate the original spike.

There’s also MaxConcurrentStreams on the server side. If a client sends more RPCs than the server’s configured maximum, gRPC will queue them — silently, from the caller’s perspective.

Under load, this queue grows and your latency climbs while your error rate stays low. You’ll think everything is fine while goroutines pile up waiting.

Context Propagation and Timeout Budgets

This one is architectural, not just a configuration knob, which makes it harder to fix after the fact.

In a distributed system, a request typically fans out. Service A calls B and C. B calls D. The latency budget at each hop matters.

So if service A sets a 2-second timeout, and Service B sets its own independent 2-second timeout to call D, you can easily exceed your end-to-end budget.

The pattern that actually works is deadline propagation: use the incoming request’s context, shorten it slightly for downstream calls, and never set a fresh timeout independent of the caller’s deadline.

func (s *service) HandleRequest(ctx context.Context, req *Request) (*Response, error) {
    // ✅ Derive from caller's context — inherits deadline
    downstreamCtx, cancel := context.WithTimeout(ctx, 800*time.Millisecond)
    defer cancel()

    result, err := s.downstream.Call(downstreamCtx, req.SubRequest)
    if err != nil {
        return nil, fmt.Errorf("downstream call: %w", err)
    }
    return &Response{Data: result}, nil
}
func (s *service) HandleRequest(ctx context.Context, req *Request) (*Response, error) {
    // ✅ Derive from caller's context — inherits deadline
    downstreamCtx, cancel := context.WithTimeout(ctx, 800*time.Millisecond)
    defer cancel()

    result, err := s.downstream.Call(downstreamCtx, req.SubRequest)
    if err != nil {
        return nil, fmt.Errorf("downstream call: %w", err)
    }
    return &Response{Data: result}, nil
}

The failure mode when you don’t do this: a downstream service hangs for 10 seconds on a slow query.

Your service has no deadline context to trigger cancellation. The goroutine sits there holding a connection from the pool. Enough of those, and your pool is exhausted.

Now requests that have nothing to do with the slow query start failing because there are no connections available.

One slow dependency, no context propagation, and you have a full-service outage.

What Makes This Hard to See

If you look at all patterns I shared here above, they tend to share a property: they are invisible at low load and catastrophic at high load.

Your load tests at 10× normal traffic won’t catch a MaxIdleConnsPerHost: 2 issue if 10× normal is still only 200 RPS.

The problem surfaces at 2000 RPS, or when you scale to 40 pods, or when a dependency slows down and connection reuse suddenly matters.

Profiling with pprof shows you CPU and memory. It won’t show you TCP connection establishment time or goroutines blocked on pool acquisition.

Here is the tooling that actually helps:

  • expvar or Prometheus histograms on db.Stats() — watch WaitCount and WaitDuration
  • Tracing with OpenTelemetry to see where time is actually going per hop
  • conntrack on the host to see TCP connection churn
  • Custom metrics on gRPC stream counts per connection

// Expose db pool stats for visibility
go func() {
    for range time.Tick(10 * time.Second) {
        stats := db.Stats()
        metrics.Gauge("db.open_connections").Set(float64(stats.OpenConnections))
        metrics.Gauge("db.in_use").Set(float64(stats.InUse))
        metrics.Counter("db.wait_count").Add(float64(stats.WaitCount))
        metrics.Histogram("db.wait_duration").Observe(stats.WaitDuration.Seconds())
    }
}()
// Expose db pool stats for visibility
go func() {
    for range time.Tick(10 * time.Second) {
        stats := db.Stats()
        metrics.Gauge("db.open_connections").Set(float64(stats.OpenConnections))
        metrics.Gauge("db.in_use").Set(float64(stats.InUse))
        metrics.Counter("db.wait_count").Add(float64(stats.WaitCount))
        metrics.Histogram("db.wait_duration").Observe(stats.WaitDuration.Seconds())
    }
}()

The common thread across all of these issues is the same: Go makes concurrency easy, which makes it easy to build systems where concurrency pressure is invisible until it’s catastrophic.

Goroutines are really cheap but network connections are not. Go’s defaults were designed for general-purpose programs, not services handling thousands of concurrent requests per process.

The gap between those two contexts is where production fires happen.

The engineers who build resilient Go services at scale aren’t doing anything exotic.

They’re just deliberate about resource limits, explicit about timeout budgets, and instrumented enough to see the system’s actual behavior — not the behavior they assumed it had.

Thanks for reading. Read these too

The Go advice I stopped following
Most “best practices” sound smart until they slow you down in production

We removed three popular Go Libraries — And the code got better
Fewer Abstractions, Better Systems: What really Happened When We Removed 3 Go Libraries

Forget perfect microservices — build this instead
Complexity feels smart — until it starts slowing everything down